首页 > 代码库 > 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设计模式之单体模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。