javascript设计模式之单体模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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设计模式之单体模式的主要内容,如果未能解决你的问题,请参考以下文章