单例模式
单例模式定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
常用的:线程池、全局缓存、浏览器的window对象等
简单的单例模式写法
const Singleton = function (name) {
this.name = name;
this.instance = null;
}
Singleton.prototype.getName = function () {
console.log(this.name);
}
Singleton.getInstance = function (name) {
console.log('this.instance',this.instance);
if (!this.instance) {
this.instance = new Singleton(name);
}
return this.instance;
}
const a = Singleton.getInstance('nnn');
const b = Singleton.getInstance('vvvv');
console.log('a', a);
console.log('b', b);
console.log(a === b); //true
简单的单例模式另一写法
const Singleton = function (name) {
this.name = name;
}
Singleton.prototype.getName = function () {
console.log(this.name);
}
Singleton.getInstance = (function () {
let instance = null;
return function (name) {
console.log('instance',instance);
if (!instance) {
instance = new Singleton(name)
}
return instance;
}
})()
const a = Singleton.getInstance('nnn');
const b = Singleton.getInstance('vvvv');
console.log('a', a);
console.log('b', b);
console.log(a === b); //true
用代理模式写一个单例模式
// 一个简单的创建div的类
const 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);
}
// 负责创建单例
const ProxySingleton = (function () {
let instance = null;
return function (html) {
if (!instance) {
instance = new CreateDiv(html);
}
return instance;
}
})()
const div = new ProxySingleton('hello-single1')
const div2 = new ProxySingleton('hello-single2')
console.log('div', div, div === div2);
惰性单例模式
仅在需要的时候创建实例。
const InertiaSingleton = function (fn) {
let instance = null
if (!instance) {
instance = fn.apply(this, arguments)
}
return instance;
}
//
const CreateDiv = function () {
let div = document.createElement('div');
div.innerHTML = 'html';
div.style.display = 'none';
document.body.appendChild(div);
return div;
}
const loginDialog = InertiaSingleton(CreateDiv);
// 当需要时再创建实例