从经典意义上来说
Singleton模式,在该实例不存在的情况下,可以通过一个方法创建一个类来实现创建类的新实例;如果实例已经存在,它会简单返回该对象的引用。Singleton不同于静态类,因为我们可以推迟他们的初始化。
var mySingleton = (function() {
var instance;
function init() {
function privateMethod() {
console.log("i am private");
}
var privateVariable = "i am also private";
var privateRandomNumber = Math.random();
return {
publickMethod: function () {
console.log("the public can see me");
},
publicProperty: "i am also public",
getRandomNumber: function () {
return privateRandomNumber;
}
};
};
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
}) ();
var myBadSingleton = (function() {
var instance;
function init() {
var privateRandomNumber = Math.random();
return {
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
getInstance: function() {
instance = init();
return instance;
}
};
})();
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log(singleA.getRandomNumber());
console.log(singleB.getRandomNumber());
console.log(singleA.getRandomNumber() === singleB.getRandomNumber()); // true
console.log("\n");
var badSingleA = myBadSingleton.getInstance();
var badSingleB = myBadSingleton.getInstance();
console.log(badSingleA.getRandomNumber());
console.log(badSingleB.getRandomNumber());
console.log(badSingleA.getRandomNumber() === badSingleB.getRandomNumber()); // false
Singleton模式的适用性描述如下:
1、当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
2、该唯一的实例应该是通过子类化可扩展的,并且客户应该无需要改代码就能使用一个扩展的实例。
在实践中
var SingletonTester = (function() {
function Singleton( options ) {
options = options || { };
this.name = "SingletonTester";
this.pointX = options.pointX || 6;
this.pointY = options.pointY || 10;
}
var instance;
var _static = {
name: "SingletonTester",
getInstance: function ( options ) {
console.log(instance + "\n");
if ( instance === undefined ) {
instance = new Singleton( options );
}
return instance;
}
};
return _static;
})();
var test1 = SingletonTester.getInstance({pointX: 15});
console.log(test1);
console.log("\n");
var test2 = SingletonTester.getInstance({pointX: 7});
console.log(test2);
结果如图:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。