JavaScript 设计模式学习 Singleton
JavaScript 设计模式学习 Singleton
发布时间:2016-12-30 来源:查字典编辑
摘要:复制代码代码如下:/*BasicSingleton.*/varSingleton={attribute1:true,attribute2:1...

复制代码 代码如下:

/* 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教程学习
编程开发子分类