JavaScript 设计模式学习 Singleton
2009-07-27 00:00
459 查看
/* 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 设计模式学习之三 Singleton(单例)模式
- 设计模式学习笔记--单例(Singleton)和多例(Multiton)
- 学习JavaScript设计模式之责任链模式
- 学习JavaScript设计模式之迭代器模式
- 【学习笔记javascript设计模式与开发实践(单例模式)----4】
- 【学习笔记javascript设计模式与开发实践(组合模式)----10】
- javascript设计模式:单例模式(Singleton)
- 【设计模式】学习笔记7:单件模式(Singleton)
- 一步步学习javascript基础篇(4):面向对象设计之创建对象(工厂、原型和构造函数等模式)
- 【学习笔记javascript设计模式与开发实践(享元模式)----12】
- javascript中Singleton设计模式的实现
- 【工作中学习1】两个设计模式:Singleton(单例)和 Adapter(适配器)
- 学习JavaScript设计模式之代理模式
- 设计模式C++学习笔记之三(Singleton单例模式)
- JavaScript 设计模式学习 Factory
- 【学习笔记javascript设计模式与开发实践(适配器模式)----17】
- 学习JavaScript设计模式之状态模式
- 学习JavaScript设计模式之状态模式
- 学习JavaScript设计模式(单例模式)