深入理解JavaScript系列(25):設計模式之單例模式

來源:互聯網
上載者:User
介紹

從本章開始,我們會逐步介紹在JavaScript裡使用的各種設計模式實現,在這裡我不會過多地介紹模式本身的理論,而只會關注實現。OK,正式開始。

在傳統開發工程師眼裡,單例就是保證一個類只有一個執行個體,實現的方法一般是先判斷執行個體存在與否,如果存在直接返回,如果不存在就建立了再返回,這就 確保了一個類只有一個執行個體對象。在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!'

上面的代碼很不錯了,但如果我們想做到只有在使用的時候才初始化,那該如何做呢?為了節約資源的目的,我們可以另外一個建構函式裡來初始化這些代碼,如下:

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) {

//設定args變數為接收的參數或者為空白(如果沒有提供的話)
var args = args || {};
//設定name參數
this.name = 'SingletonTester';
//設定pointX的值
this.pointX = args.pointX || 6; //從接收的參數裡擷取,或者設定為預設值
//設定pointY的值
this.pointY = args.pointY || 10;

}

//執行個體容器
var instance;

var _static = {
name: 'SingletonTester',

//擷取執行個體的方法
//返回Singleton的執行個體
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;

var uni = new Universe();

Universe.prototype.everything = true;

var uni2 = new Universe();

console.log(uni.nothing); // true
console.log(uni2.nothing); // true
console.log(uni.everything); // true
console.log(uni2.everything); // true
console.log(uni.constructor === Universe); // true

方式4:
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

參考資料

https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/singleton.html

http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

 

 

轉自:湯姆大叔

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.