JavaScript 設(shè)計模式學(xué)習(xí) Singleton
更新時間:2009年07月27日 17:41:07 作者:
JavaScript設(shè)計模式學(xué)習(xí) Singleton
復(fù)制代碼 代碼如下:
/* Basic Singleton. */
var Singleton = {
attribute1: true,
attribute2: 10,
method1: function() {
},
method2: function(arg) {
}
};
單件模式最主要的用途之一就是命名空間:
/* GiantCorp namespace. */
var GiantCorp = {};
GiantCorp.Common = {
// A singleton with common methods used by all objects and modules.
};
GiantCorp.ErrorCodes = {
// An object literal used to store data.
};
GiantCorp.PageHandler = {
// A singleton with page specific methods and attributes.
};
利用閉包在單件模式中實現(xiàn)私有方法和私有變量:
GiantCorp.DataParser = (function() {
// Private attributes.
var whitespaceRegex = /\s+/;
// Private methods.
function stripWhitespace(str) {
return str.replace(whitespaceRegex, '');
}
function stringSplit(str, delimiter) {
return str.split(delimiter);
}
// Everything returned in the object literal is public, but can access the
// members in the closure created above.
return {
// Public method.
stringToArray: function(str, delimiter, stripWS) {
if(stripWS) {
str = stripWhitespace(str);
}
var outputArray = stringSplit(str, delimiter);
return outputArray;
}
};
})(); // Invoke the function and assign the returned object literal to
// GiantCorp.DataParser.
實現(xiàn)Lazy Instantiation 單件模式:
MyNamespace.Singleton = (function() {
var uniqueInstance; // Private attribute that holds the single instance.
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
if(!uniqueInstance) { // Instantiate only if the instance doesn't exist.
uniqueInstance = constructor();
}
return uniqueInstance;
}
}
})();
MyNamespace.Singleton.getInstance().publicMethod1();
您可能感興趣的文章:
- JavaScript設(shè)計模式之工廠模式和構(gòu)造器模式
- JavaScript 設(shè)計模式 安全沙箱模式
- JavaScript設(shè)計模式之觀察者模式(發(fā)布者-訂閱者模式)
- JavaScript 設(shè)計模式之組合模式解析
- javascript設(shè)計模式之解釋器模式詳解
- JavaScript設(shè)計模式之原型模式(Object.create與prototype)介紹
- 學(xué)習(xí)JavaScript設(shè)計模式(鏈?zhǔn)秸{(diào)用)
- JavaScript設(shè)計模式之單例模式實例
- 常用的javascript設(shè)計模式
- JavaScript 設(shè)計模式學(xué)習(xí) Factory
- JavaScript編程設(shè)計模式之構(gòu)造器模式實例分析
相關(guān)文章
JavaScript面向?qū)ο?極簡主義法minimalist approach)
荷蘭程序員 Gabor de Mooij 提出了一種比 Object.create ()更好的新方法,他稱這種方法為極簡主義法(minimalist approach)。這也是我推薦的方法2012-07-07JavaScript面向?qū)ο笾甈rototypes和繼承
本文翻譯自微軟的牛人Scott Allen Prototypes and Inheritance in JavaScript ,本文對到底什么是Prototype和為什么通過Prototype能實現(xiàn)繼承做了詳細(xì)的分析和闡述,是理解JS OO 的佳作之一2012-07-07javascript中的對象創(chuàng)建 實例附注釋
為了讓你的js代碼更加的專業(yè)與代碼的條理性,很多情況下都是定義成對象的方式來書寫代碼,想深入的朋友可以參考下。2011-02-02javascript 設(shè)計模式之單體模式 面向?qū)ο髮W(xué)習(xí)基礎(chǔ)
單體是在腳本加載時創(chuàng)建的,能將一系列有關(guān)聯(lián)的變量和方法組織為一個邏輯單元,邏輯單元里面的內(nèi)容通過單一的變量進(jìn)行訪問,也是筆記基礎(chǔ)與常用的面向?qū)ο蟮亩x方法。2010-04-04