從本章開始,我們會逐步介紹在JavaScript中使用的各種設計模式實現。這裡不會過多探討模式本身的理論,而只關注如何實現。
在傳統工程師眼裡,單例就是保證一個類只有一個實例:先判斷實例是否存在,存在就直接返回,不存在就創建後再返回。而在JavaScript裡,單例作為一個命名空間提供者,從全局命名空間中提供一個唯一的訪問點來訪問該物件。
JavaScript實現單例的方式有很多,最簡單的是使用物件字面量,其字面量裡可以包含大量屬性和方法:
var mySingleton = {
property1: "something",
property2: "something else",
method1: function () {
console.log('hello world');
}
};
以後要擴展時,可以添加自己的私有成員和方法,用閉包把變量和函數封裝起來,只暴露想暴露的public成員:
var mySingleton = function () {
/* 這裡聲明私有變量和方法 */
var privateVariable = 'something private';
function showPrivate() {
console.log(privateVariable);
}
/* 公有變量和方法(可訪問私有成員) */
return {
publicMethod: function () {
showPrivate();
},
publicVar: 'the public can see this!'
};
};
var single = mySingleton();
single.publicMethod(); // 輸出 'something private'
console.log(single.publicVar); // 輸出 'the public can see this!'
如果想做到「只有使用時才初始化」,以節約資源,可以把初始化放到一個函數裡,透過getInstance按需創建:
var Singleton = (function () {
var instantiated;
function init() {
/* 這裡定義單例代碼 */
return {
publicMethod: function () {
console.log('hello world');
},
publicProperty: 'test'
};
}
return {
getInstance: function () {
if (!instantiated) {
instantiated = init();
}
return instantiated;
}
};
})();
Singleton.getInstance().publicMethod();
單例一般用於系統間各種模式的通信協調上,下面是一個最佳實踐:
var SingletonTester = (function () {
function Singleton(args) {
var args = args || {};
this.name = 'SingletonTester';
this.pointX = args.pointX || 6;
this.pointY = args.pointY || 10;
}
var instance;
var _static = {
name: 'SingletonTester',
getInstance: function (args) {
if (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
return _static;
})();
var singletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // 輸出 5
方法1:把實例緩存到構造函數的靜態屬性上。
function Universe() {
if (typeof Universe.instance === 'object') {
return Universe.instance;
}
this.start_time = 0;
this.bang = "Big";
Universe.instance = this;
// 隱式返回 this
}
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true
方法2:在構造函數內部緩存實例,並重寫構造函數本身。
function Universe() {
var instance = this;
this.start_time = 0;
this.bang = "Big";
Universe = function () {
return instance;
};
}
var uni = new Universe();
var uni2 = new Universe();
uni.bang = "123";
console.log(uni === uni2); // true
console.log(uni2.bang); // 123
方法3:重寫構造函數並延後處理原型屬性,能同時保留原型鏈。
function Universe() {
var instance;
Universe = function Universe() {
return instance;
};
Universe.prototype = this;
instance = new Universe();
instance.constructor = Universe;
instance.start_time = 0;
instance.bang = "Big";
return instance;
}
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true
Universe.prototype.nothing = true;
console.log(uni.nothing); // true
方法4:用IIFE封裝實例,構造函數內部判斷是否已存在。
var Universe;
(function () {
var instance;
Universe = function Universe() {
if (instance) { return instance; }
instance = this;
this.start_time = 0;
this.bang = "Big";
};
}());
var a = new Universe();
var b = new Universe();
alert(a === b); // true
a.bang = "123";
alert(b.bang); // 123
以上幾種方式各有側重,可根據是否需要延遲初始化、是否保留原型鏈等需求靈活選用。