国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JavaScript 設計模式學習 Singleton

2019-11-21 01:14:02
字體:
來源:轉載
供稿:網友
復制代碼 代碼如下:

/* 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();
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 甘孜县| 汪清县| 宜丰县| 柳河县| 浦城县| 哈密市| 平顺县| 罗江县| 屏东市| 林西县| 攀枝花市| 牙克石市| 庆安县| 静宁县| 彭州市| 巴彦淖尔市| 盖州市| 民丰县| 新昌县| 林芝县| 宣城市| 登封市| 深水埗区| 农安县| 周口市| 龙门县| 洛阳市| 瓮安县| 茶陵县| 阿拉尔市| 大庆市| 连州市| 沐川县| 长兴县| 离岛区| 阿拉善盟| 新干县| 潢川县| 佛坪县| 建德市| 图木舒克市|