- 类只有一个实例
- 可以绑定在全局实例,也可以通过闭包来私有变量,还可以通过es6的symbol
var Singleton = function(name) {
this.name = name
this.instance = null
}
Singleton.getInstance = function(name) {
if(!this.instance) {
this.instance = new Singleton(name)
}
return this.instance
}
var instance1 = Singleton.getInstance('a')
var instance2 = Singleton.getInstance('b')
console.log(instance1 === instance2)
//使用new关键字实现单例
var Singleton = (function(name) {
let instance = null
return function(name) {
if(!instance) {
this.name = name
instance = this
}
return instance
}
})()
var instance1 = new Singleton('a')
var instance2 = new Singleton('b')
console.log(instance1 === instance2)
//惰性单例
var Singleton = function(fn) {
let instance;
return function() {
return instance || (instance = fn.apply(this, arguments))
}
}
function createObj(name) {
return {
name: name
}
}
var createSingleObj = Singleton(createObj)
var instance1 = createSingleObj('a')
var instance2 = createSingleObj('b')
console.log(instance1 === instance2)
- 工厂模式用来创建对象,实用场景
- 对象构建十分复杂
- 需要依赖具体环境创建不同实例
- 处理大量具有相同属性的小对象
var Factory = (function () {
let instance = function(name) {
this.name = name
}
return function(name) {
return new instance(name)
}
})()
var f1 = new Factory('a')
var f2 = new Factory('b')
console.log(f1 === f2)