首页 > 代码库 > javascript设计模式之单体模式

javascript设计模式之单体模式

一入前端深似海,刚入前端,以为前端只是div+css布局外加jquery操作DOM树辣么简单。伴随着对前端学习的深入,发现前端也是博大精深,而且懂得越多,才发现自己越无知,所以一定不能停下脚步的学习。原来前端也有设计模式,那么开始了解吧!

今天来学最简单的单体模式,其实就是简单的Object扩展

var calcYourShengXiao={       solar : ["","","","","","","","","",""],       moon : ["","","","","","","","","","","",""],       animal : ["","","","","","","","","","","",""],       output:function(year){           var sr=(year-1924)%10;           var mr=(year-1924)%12;           console.log("你是"+this.solar[sr]+this.moon[mr]+"出生 属"+this.animal[mr]);       }}calcYourShengXiao.output(1990);

上边就是一个最基本的单体模型,把一个功能模块相关的数据和方法用一个对象表示,便于阅读和管理,同时减少了全局变量的使用。

还可以通过闭包实现一个惰性实例单体。

对于资源密集型的或配置开销甚大的单体,也许更合理的做法是将其实例化推迟到需要使用它的时候。这种技术被称为“惰性加载”(lazy loading)。

所以对于可能需要加载大量数据的单体,选择惰性加载效率会更高。如下实例

var sxCalc=(function(){      var obj={           solar : ["","","","","","","","","",""],           moon : ["","","","","","","","","","","",""],           animal : ["","","","","","","","","","","",""],           calcYourShengXiao:function(year){              var sr = (year-1924)%10;              var mr = (year-1924)%12;              console.log("你是"+this.solar[ sr>=0 ? sr:10+sr ]+this.moon[ mr>=0 ? mr:12+mr]+"出生 属"+this.animal[ mr>=0 ? mr:12+mr]);           }      };      return {          get:function(){              return obj;          }     }})()sxCalc.get().calcYourShengXiao(1990)

 

javascript设计模式之单体模式