基本思想:解决多次创建对象的问题,缓存一个对象实例,返回缓存来代替创建。
简单单例写法
// 1.
let Singleton = function(name) {
this.name = name
this.instance = null
}
Singleton.prototype.getName = function() {
return this.name
}
Singleton.getInstance = function(name) {
if (!this.instance) {
this.instance = new Singleton(name)
}
return this.instance
}
let s1 = Singleton.getInstance('a')
let s2 = Singleton.getInstance('b')
console.log(s1 === s2) */
// 2.
/* let Singleton = function(name) {
this.name = name
}
Singleton.prototype.getName = function() {
return this.name
}
Singleton.getInstance = (function(name) {
this.instance = null
return function() {
if (!this.instance) {
this.instance = new Singleton(name)
}
return this.instance
}
})()
let s1 = Singleton.getInstance('a')
let s2 = Singleton.getInstance('b')
console.log(s1 === s2)
以上问题是用户需要知道这是一个单类,不透明。
透明单例
let CreateDiv = (function(){
let instance
let CreateDiv = function(html) {
if (instance) {
return instance
}
this.html = html
this.init()
return instance = this
}
CreateDiv.prototype.init = function() {
let div = document.createElement('div')
div.innerHTML = this.html
document.body.appendChild(div)
}
return CreateDiv
})()
let d1 = new CreateDiv('1')
let d2 = new CreateDiv('2')
console.log(d1 === d2)
使用了匿名函数和闭包,职责不分明
使用代理
分离单例模式和初始化创建对象两个职能
let CreateDiv = function(html) {
this.html = html
this.init()
}
CreateDiv.prototype.init = function() {
let div = document.createElement('div')
div.innerHTML = this.html
document.body.appendChild(div)
}
let ProxyCreateDiv = (function() {
let instance
return function(html) {
if (!instance) {
instance = new CreateDiv(html)
}
return instance
}
})()
let d1 = new ProxyCreateDiv('a')
let d2 = new ProxyCreateDiv('b')
console.log(d1 === d2)
惰性单例
在需要的时候才创建对象实例
惰性单例通用模式
let getInstance = function(fn) {
let res
return function() {
return res || (res = fn.apply(this, arguments))
}
}
使用
...
<button onclick="d1()">点我</button>
...
let CreateDiv = function(html) {
this.html = html
}
CreateDiv.prototype.init = function() {
console.log(this)
let div = document.createElement('div')
div.innerHTML = this.html
document.body.appendChild(div)
return div
}
let c = new CreateDiv('a')
let d1 = getInstance(c.init).bind(c)
类里面的单例模式1
写在构造器里面
class A {
static _instance = null
constructor(props) {
if(!A._instance) {
A._instance = new A(props)
}
return A._instance
}
}
const a = new A()
类里面的单例模式2
使用static对单例代码分离及结构优化
class A {
_instance = null
constructor(props) {
// super()
}
static getInstance(props) {
if(!this._instance) {
this._instance = new A(props)
}
return this._instance
}
}
const a = A.getInstance()
类生成器
react中的高级类
const CreateClass = Sup => class extends Sup {
constructor() {
super();
}
}
const aCls = new (CreateClass(A))()
const bCls = new (CreateClass(B))()
// A,B为类
1264

被折叠的 条评论
为什么被折叠?



