Skip to content

单例模式(Singleton) #2

@twosugar

Description

@twosugar

单例模式,就是保证一个类仅有一个实例,并且提供一个访问它的全局访问点,就是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 

每天学习一点点~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions