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

JavaScript 設計模式學習 Singleton

復制代碼 代碼如下:
/* 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.
};
利用閉包在單件模式中實現私有方法和私有變量:
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.
實現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技術JavaScript 設計模式學習 Singleton,轉載需保留來源!

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

主站蜘蛛池模板: 方山县| 泽普县| 喀喇沁旗| 内乡县| 富顺县| 辽中县| 玉环县| 临沭县| 广州市| 大宁县| 阿拉善盟| 宜良县| 西乌珠穆沁旗| 贺兰县| 通许县| 达拉特旗| 绥阳县| 津南区| 芜湖市| 尉氏县| 嘉兴市| 勐海县| 石阡县| 广河县| 新丰县| 珠海市| 房山区| 临城县| 南江县| 黔江区| 太康县| 武平县| 宁晋县| 汉源县| 宁城县| 金昌市| 栾川县| 梓潼县| 城口县| 阳朔县| 绵竹市|