所谓单例模式,即是限定一个对象生成的实例数只有一个,这个唯一的实例就是单例。
举个最简单的例子:
1 2 3 4 5 6 7
| var user = { firstName: 'John', lastName: 'Doe', sayName: function() { return this.firstName + ' ' + this.lastName; } };
|
这个user就是一个单例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| var mySingleton = (function () {
var instance;
function init() {
function privateMethod(){ console.log( "I am private" ); }
var privateVariable = "Im also private";
return {
publicMethod: function () { console.log( "The public can see me!" ); },
publicProperty: "I am also public" };
};
return {
getInstance: function () {
if ( !instance ) { instance = init(); }
return instance; }
};
})();
var singleA = mySingleton.getInstance(); var singleB = mySingleton.getInstance(); console.log( singleA === singleB );
|
参考:
http://robdodson.me/javascript-design-patterns-singleton/