js 单例模式笔记

时间:2023-03-08 22:54:54
js 单例模式笔记

单例指一个类只有一个实例,这个类自行创建这个实例。

利用对象字面量直接生成一个单例:

var singleton = {
prop: 1,
method: function(){
console.log(a); //1
}
}

严格的说对象字面量可能不算单例模式,生成单例是对象字面量的作用(已经被封装),而单例模式是一个设计模式(需要自行构思或设计)。

在类内部用new生成实例的单例模式:

var instance;
var foo = function(){
if(!instance){
instance = new Singleton();
}
return instance;
function Singleton(){
this.name = 'single';
this.method = function(){
console.log(this.name);
}
};
} var a = foo();
var b = foo();
a.method(); //single
console.log(a === b); //true

单例模式只要检测一个实例是否被生成。假如没有实例,则生成实例。假如已经生成则返回这个实例。保证这个类只有这一个实例。

由于hoisting,函数会提前声明,所以 singleton 函数放在哪都没所谓,但是每次调用都会声明函数singleton,可能会不够优雅。

由于new关键字是执行函数,同时this指向这个对象,所以可以判断类的this是否赋值给instance:

var instance;
var Singleton = function(){
if(instance){
return instance;
}
instance = this;
this.name = 'single';
this.method = function(){
console.log(this.name);
}
} var a = new Singleton();
var b = new Singleton();
a.method(); //single
console.log(a === b); //true

这个例子中,把instance指向了Singleton这个类,然后在类外部通过new来实例化,和上例中的new异曲同工。由于是通过修改this来达到检测是否执行过Singleton类,所以个人感觉不够语义化。

上面的例子用es6重构的写法。

类内部new生成单例:

var instance;
class foo{
static Singleton(){
if(!instance){
instance = new foo();
}
return instance;
}
method(){
this.name = 'single';
console.log(this.name);
}
} var a = foo.Singleton();
var b = foo.Singleton();
a.method(); //single
console.log(a === b); //true

  

修改this指向生成单例:

var instance;
class foo{
constructor(){
if(!instance){
this.Singleton();
}
return instance;
}
Singleton(){
instance = this;
this.name = 'single';
this.method = function(){
console.log(this.name);
}
}
} var a = new foo();
var b = new foo();
a.method(); //single
console.log(a === b); //true

  

当然除了这两种以外还有别的方式能实例化一个单例。