当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 设计模式学习 Singleton

Javascript
用户注册常用javascript代码
JavaScript 事件监听实例代码[兼容IE,firefox] 含注释
javascript appendChild,innerHTML,join性能比较代码
JavaScript 继承详解 第一篇
javascript 控制 html元素 显示/隐藏实现代码
Javascript 判断函数类型完美解决方案
获取URL地址中的文件名和参数的javascript代码
js 获取浏览器高度和宽度值(多浏览器)
FF IE兼容性的修改小结
JS URL传中文参数引发的乱码问题
javascript 24小时弹出一次的代码(利用cookies)
ie focus bug 解决方法
javascript concat数组累加 示例
javascript 触发事件列表 比较不错
当文本框的值发生改变时,触发事件,在IE中有效
javascript 操作table的特性
jquery判断单个复选框是否被选中的代码
关于javascript中的parseInt使用技巧
JavaScript 密码强度判断代码
js跨域和ajax 跨域问题的实现思路

Javascript 中的 JavaScript 设计模式学习 Singleton


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 241 ::
收藏到网摘: n/a

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();