JavaScript的單例模式 (singleton in Javascript)
更新時間:2010年06月11日 00:28:44 作者:
JavaScript的單例模式 (singleton in Javascript)
單例模式的基本結(jié)構(gòu):
MyNamespace.Singleton = function() {
return {};
}();
比如:
MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();
但是,上面的Singleton在代碼一加載的時候就已經(jīng)建立了,怎么延遲加載呢?想象C#里怎么實現(xiàn)單例的:)采用下面這種模式:
MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();
具體來說,把創(chuàng)建單例的代碼放到constructor里,在首次調(diào)用的時候再實例化:
完整的代碼如下:
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;
}
}
})();
復(fù)制代碼 代碼如下:
MyNamespace.Singleton = function() {
return {};
}();
比如:
復(fù)制代碼 代碼如下:
MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();
但是,上面的Singleton在代碼一加載的時候就已經(jīng)建立了,怎么延遲加載呢?想象C#里怎么實現(xiàn)單例的:)采用下面這種模式:
復(fù)制代碼 代碼如下:
MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();
具體來說,把創(chuàng)建單例的代碼放到constructor里,在首次調(diào)用的時候再實例化:
完整的代碼如下:
復(fù)制代碼 代碼如下:
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;
}
}
})();
相關(guān)文章
編寫可維護面向?qū)ο蟮腏avaScript代碼[翻譯],學習js面向?qū)ο缶帉懙呐笥芽梢詤⒖枷隆?/div> 2011-02-02
JavaScript接口實現(xiàn)代碼 (Interfaces In JavaScript)
接口是面向?qū)ο缶幊汤锏闹匾匦?,遺憾的是JavaScript并沒有提供對接口的支持!怎么實現(xiàn)接口呢?2010-06-06
AppBaseJs 類庫 網(wǎng)上常用的javascript函數(shù)及其他js類庫寫的
AppBaseJs類庫。一個借鑒了網(wǎng)上常用的函數(shù)及其他js類庫寫的,方便大家的調(diào)用。2010-03-03
一個cssQuery對象 javascript腳本實現(xiàn)代碼
原創(chuàng)的一個cssQuery對象,類似于jQuery的$函數(shù)通過css選擇器選擇DOM元素,目前還不支持xPath語法2009-07-07最新評論

