JavaScript的单例模式 (singleton in Javascript)
更新时间:2010年06月11日 00:28:44 作者:
JavaScript的单例模式 (singleton in Javascript)
单例模式的基本结构:
MyNamespace.Singleton = function() {
return {};
}();
比如:
MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();
但是,上面的Singleton在代码一加载的时候就已经建立了,怎么延迟加载呢?想象C#里怎么实现单例的:)采用下面这种模式:
MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();
具体来说,把创建单例的代码放到constructor里,在首次调用的时候再实例化:
完整的代码如下:
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 = function() {
return {};
}();
比如:
复制代码 代码如下:
MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();
但是,上面的Singleton在代码一加载的时候就已经建立了,怎么延迟加载呢?想象C#里怎么实现单例的:)采用下面这种模式:
复制代码 代码如下:
MyNamespace.Singleton = (function() {
function constructor() { // All of the normal singleton code goes here.
...
}
return {
getInstance: function() {
// Control code goes here.
}
}
})();
具体来说,把创建单例的代码放到constructor里,在首次调用的时候再实例化:
完整的代码如下:
复制代码 代码如下:
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;
}
}
})();
相关文章
JavaScript为对象原型prototype添加属性的两种方式
为对象原型prototype添加属性的的方法, 需要的朋友可以参考下。2010-08-08JavaScript面向对象(极简主义法minimalist approach)
荷兰程序员 Gabor de Mooij 提出了一种比 Object.create ()更好的新方法,他称这种方法为极简主义法(minimalist approach)。这也是我推荐的方法2012-07-07
最新评论