bob体育官方平台
JavaScript 设计模式学习 Singleton_js面向对象_脚本之家

复制代码 代码如下: /* Basic Singleton. */ var Singleton = { attribute1: true, attribute2: 10, method1: function(卡塔尔 { }, method2: function { } }; 单件格局最器重的用项之风华正茂正是命名空间: /* 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 = { // Private attributes. var whitespaceRegex = /s+/; // Private methods. function stripWhitespace { return str.replace; } function stringSplit { return str.split; } // 伊芙rything 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 { str = stripWhitespace; } var outputArray = stringSplit; return outputArray; } }; }State of Qatar(卡塔尔国; // Invoke the function and assign the returned object literal to // GiantCorp.DataParser. 达成Lazy Instantiation 单件格局: MyNamespace.Singleton = { var uniqueInstance; // Private attribute that holds the single instance. function constructor(State of Qatar { // All of the normal singleton code goes here. ... } return { getInstance: function(卡塔尔(قطر‎ { if { // Instantiate only if the instance doesn't exist. uniqueInstance = constructor(卡塔尔(قطر‎; } return uniqueInstance; } } }卡塔尔国(State of Qatar; MyNamespace.Singleton.getInstance;

具体来说,把创设单例的代码放到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;
}
}
})();

单例方式的主导组织:

不过,下边包车型大巴Singleton在代码BlackBerry载的时候就早就组建了,怎么延迟加载呢?想象C#里怎么落实单例的:卡塔尔(قطر‎采纳下边这种情势:

MyNamespace.Singleton = (function() {
return { // Public members.
publicAttribute1: true,
publicAttribute2: 10,
publicMethod1: function() {
...
},
publicMethod2: function(args) {
...
}
};
})();

复制代码 代码如下:

复制代码 代码如下:

返回顶部