色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

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ù)JavaScript 設(shè)計模式學(xué)習(xí) Singleton,轉(zhuǎn)載需保留來源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 建阳市| 沁水县| 饶河县| 四会市| 阳江市| 綦江县| 孙吴县| 松江区| 高阳县| 喀喇沁旗| 曲麻莱县| 巢湖市| 永城市| 浑源县| 孟村| 伊川县| 福清市| 三门峡市| 饶阳县| 巴彦淖尔市| 广德县| 泸西县| 乌鲁木齐市| 九龙城区| 都江堰市| 林西县| 砀山县| 施秉县| 太原市| 安仁县| 巫山县| 黑水县| 淮南市| 章丘市| 通榆县| 赣州市| 罗城| 台中市| 湄潭县| 建阳市| 甘洛县|