1.什么是单体?
单体是一个用来划分命名空间并将一批方法和属性组织在一起的对象, 如果它可以被实例化,那么它只能被实例化一次.
2.简单的单体
最简单的单体实际上就是一个声明的对象.
var MyNameSpace = {};
MyNameSpace.Singleton = { publicAttr1: true, publicAttr2: 20, publicMethod1: function () { }, publicMethod2: function () { } };3. 带有私有变量的单体
带有私有变量的单体需要用到闭包.
MyNameSpace.SingletonWithPrivateMem = function () {
var privateAttr1 = 10; return { publicAttr1: true, publicAttr2: 20, publicMethod1: function () { // we can access privateAttr1 here }, publicMethod2: function () { // we can access privateAttr1 here } }; }();4.需要惰性实例化的单体
惰性实例化的单体就是使用时进行创建, 需要为这个单体增加一个getInstance()方法.
MyNameSpace.LazyCreateSingleton = function () {
var instance = null; function constructor() { var privateAttr1 = 10; return { publicAttr1: true, publicAttr2: 20, publicMethod1: function () { // we can access privateAttr1 here }, publicMethod2: function () { // we can access privateAttr1 here } }; };return {
getInstance: function () { if (!instance) { instance = constructor(); } return instance; } } }();5.单体的应用
考虑不同的浏览器,创建XHR对象.
MyNameSpace.XhrFactory = (function () {
var standard = { createXhrObject: function () { return new XMLHttpRequest(); } };var activeXNew = {
createXhrObject: function () { return new ActiveXObject('Msxml2.XMLHTTP'); } }; var activeXOld = { createXhrObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } };// branch test
var testOjbect = null; try { testOjbect = standard.createXhrObject(); return standard; } catch (e) { try { testObject = activeXNew.createXhrObject(); return activeXNew; } catch (e) { try { testObject = activeXOld.createXhrObject(); return activeXOld; } catch (e) { throw new Error("no XHR object found in this enviroment"); } } }})();