Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单例模式(Singleton) #2

Open
twosugar opened this issue Apr 1, 2019 · 0 comments
Open

单例模式(Singleton) #2

twosugar opened this issue Apr 1, 2019 · 0 comments

Comments

@twosugar
Copy link
Owner

twosugar commented Apr 1, 2019

单例模式,就是保证一个类仅有一个实例,并且提供一个访问它的全局访问点,就是getInstance方法。单例模式又分为懒汉模式和饿汉模式。
懒汉式:只有用到需要实例的地方才实例。

const singleton = (function() {
  var instance = null //定义实例
  var a = 1; 
  function singleton() {
    // xxx
    this.name = 'hello' 
  }

  function getInstance() {
    if(instance == null) {
      instance = new singleton()
    }
    return instance
  }

  function getData() {
    // xxx
    return a;  //外部直接访问a访问不到,只有通过这种方式
  }

  return {
    getInstance,
    getData
  }

})()

console.log(singleton.a) //undefined
console.log(singleton.getData()) // 1
console.log(singleton. getInstance().name) // hello 

饿汉式:调用就创建

const singleton = (function() {
  var a = 1; 
  function singleton() {
    // xxx
    this.name = 'hello' 
  }

  var instance = new singleton() //定义实例

  function getInstance() {
    return instance
  }

  function getData() {
    // xxx
    return a;  //外部直接访问a访问不到,只有通过这种方式
  }

  return {
    getInstance,
    getData
  }

})()

console.log(singleton.a) //undefined
console.log(singleton.getData()) // 1
console.log(singleton. getInstance().name) // hello 

每天学习一点点~~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant