javascript设计模式之单体模式
单体模式属于js设计模式中的创建对象型模式,它保证一个特定类只会有一个实例
当我们使用对象字面量的语法创建对象时,自然是一个单体;
当我们使用构造器创建对象时,我们通常有两种方法去实现单体模式
第一种是使用全局变量做当前对象的保存
第二种是使用构造器的静态属性,代码如下:
Function Universe () {
if(typeof Universe.instance !== 'undefined'){
return Universe.instance;
}
this.bang = 'big';
Universe.instance = this;
return this;
}
第三种是使用闭包保存当前对象this,代码如下:
Function Universe () {
if(typeof Universe.instance !== 'undefined'){
return Universe.instance;
}
this.bang = 'big';
Universe.instance = this;
return this;
}