Skip to content

Latest commit

 

History

History
51 lines (39 loc) · 1.04 KB

设计模式-单例模式.md

File metadata and controls

51 lines (39 loc) · 1.04 KB

单例模式的定义: 保证一个类仅有一个实例,并提供一个全局访问它的全局访问点。

单例模式是一种常用的模式,有一些对象我们天生只需要一个,比如线程池、全局缓存、浏览器中的 window 对象。

实现单例模式

var Singleton = function(name) {
    this.name = name
}
Singleton.instance = null
Singleton.prototype.getName = function() {
  alert(this.name)
}

Singleton.getInstance = function(name) {
  if(!this.instance){
      this.instance = new Singleton(name)
  }
  return this.instance
}

var a = Singleton.getInstance('a')
var b = Singleton.getInstance('b')

alert(a === b) // true

ES6 实现单例模式

class Singleton {
  constructor(name){
      this.name = name
  }
  
  static instance 
  
  static getInstance = function() {
    if(!Singleton.instance){
          Singleton.instance = new Singleton(name)
      }
      return Singleton.instance
  }
}

let a = Singleton.getInstance('a')
let b = Singleton.getInstance('b')

alert(a === b) // true