单例模式:多次实例化,最终也只有一个实例被创建,所有的方法和属性,都只能通过这个被创建的实例进行调用。
1.实现方式一:用一个变量来标志当前的类已经创建过对象
用一个变量来标志当前的类已经创建过对象,如果下次获取当前类的实例时,直接返回之前创建的对象即可文章来源:https://uudwc.com/A/GdEjA
//通过一个变量来标识实例已经被创建,如果已经创建过实例就不再创建
function Singleton(name){
this.name = name;
this.instance = null;
}
Singleton.prototype.getName = function(name){
console.log(name);
}
Singleton.getInstance = function(name){
if(!this.instance) this.instance = new Singleton(name);
return this.instance;
}
let a = Singleton.getInstance("a");
let b = Singleton.getInstance("b");
console.log(a === b);
2.实现方式二:闭包
function Singleton(name){
this.name = name;
this.instance = null;
}
Singleton.prototype.getName = function(name){
console.log(name);
}
Singleton.getInstance = (function(name){
return function(name){
if(!this.instance) this.instance = new Singleton(name);
return this.instance;
}
})()
let a = Singleton.getInstance("a");
let b = Singleton.getInstance("b");
console.log(a === b);
3.实现方式三:闭包+构造函数
function CreateSingleton(name){
this.name = name;
this.getName(name);
}
CreateSingleton.prototype.getName = function(name){
console.log(name);
}
const Singleton = (function(name){
let instance = null;
return function(name){
if(!instance) instance = new CreateSingleton(name);
return instance;
}
})();
let a = new Singleton("a");
let b = new Singleton("b");
console.log(a === b);
文章来源地址https://uudwc.com/A/GdEjA