javascript设计模式初探--单例模式

来源:互联网 发布:windows清理助手64 编辑:程序博客网 时间:2024/06/01 19:37
一、什么是单例模式
Ensure a class only has one instance, and provide a global point of access to it.,即 “保证一个类仅有一个实例,并提供一个访问它的全局访问点”。
二、单例模式的简单实现:
用一个变量来标志当前是否已经为一个类创建过对象,如果是,则在下一次获取该类时,直接返回之前创建的对象。
var Singleton = function( name ){this.name = name;this.instance = null;};Singleton.prototype.getName = function(){alert ( this.name );};Singleton.getInstance = function( name ){if ( !this.instance ){this.instance = new Singleton( name );}return this.instance;};var a = Singleton.getInstance( 'sven1' );var b = Singleton.getInstance( 'sven2' );alert ( a === b ); // true
三、单例模式有什么用?
主要有三点:减少全局变量,分支(branching)以及其他开发中某个对象只需要一次的情况。
1、减少全局变量由于javascript的设计者在设计之初的失误,导致全局变量成为js中最为诟病的特特性,使用单例模式创建统一的命名空间,降低全局变量带来的污染,同时组合在一起的形式便于代码管理。
var NAMESPACE = {};NAMESPACE.login = function() {      // do some login shtuffs}NAMESPACE.logout = function() {      // do some logout shtuffs}NAMESPACE.addToCart = function() {      // blah, blah blah...}
带有私有变量(又称module pattern)
var myInstance = (function() {  var privateVar = '';  function privateMethod () {    // 这里是代码  }  return { //公共接口    publicMethod1: function () {      // 这里是代码    },    publicMethod2: function () {     //这里是代码    }  };})();
2、分支(branching):Branching is a technique that allows you to encapsulate browser differences into dynamic methods that get set at run-time. 分支是一种允许你将不同的浏览器差异封装入动态方法的技术(例子:不同浏览器XHR请求)
/* SimpleXhrFactory singleton, step 2. */var SimpleXhrFactory = (function() {// The three branches.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');}};// To assign the branch, try each method; return whatever doesn't fail.var testObject;try {testObject = standard.createXhrObject();return standard; // Return this if no error was thrown.}catch(e) {try {testObject = activeXNew.createXhrObject();return activeXNew; // Return this if no error was thrown.}catch(e) {try {testObject = activeXOld.createXhrObject();return activeXOld; // Return this if no error was thrown.}catch(e) {throw new Error('No XHR object found in this environment.');}}}})();
3、开发中某个对象只需要一次的情况,线程池、全局缓存、浏览器中的window 对象等,举一个自己用谷歌地图api的例子(完整代码看这里),创建唯一一个展示的marker信息的infowindow节点,当在某个marker上打开infowindow的时候显示内容。
function populateInfoWindow(marker, infowindow){    //检查infowindow没有在marker上打开    if (infowindow.marker != marker){    //设置infowindow内容    infowindow.setContent('<div>' + marker.title  ‘</div>');    //设置marker    infowindow.marker = marker;    //当Infowindow被关闭的时候确保marker属性清除    infowindow.addListener('closeclick',function(){    infowindow.setMarker = null;    });//在特定的marker上打开infowindowinfowindow.open(map, marker);}
四、单例模式的缺点 违反了“单一职责原则”,代码紧密耦合,在许多情况下难以通过测试找出问题所在,模块的相互依赖使得难以进行单元测试。
五、关于设计模式的争论:
设计模式用与不用的问题,见仁见智,stackoverfolw上有这样一个回答,深以为然:
Some coding snobs look down on them as just a glorified global. In the same way that many people hate the goto statement there are others that hate the idea of ever using a global. I have seen several developers go to extraordinary lengths to avoid a global because they considered using one as an admission of failure. Strange but true.
In practice the Singleton pattern is just a programming technique that is a useful part of your toolkit of concepts. From time to time you might find it is the ideal solution and so use it. But using it just so you can boast about using a design pattern is just as stupid as refusing to ever use it because it is just a global.
最后,作为一个刚开始学习设计模式的小萌新,以《head first 设计模式》的一段话提醒自己:
使用模式的心智:
初学者的心智:“我需要为hello world找到一个模式”:
初学者到处使用模式。这很好;初学者可以借此培养许多使用模式的实战经验。初学者也认为,我是用阅读模式,我的设计就越好。初学者将慢慢认识到并非如此。所有的设计都应该尽量保持简单,需要在需要实践扩展的地方才值得需用复杂性和模式。
中级人员的心智:"或许这里我需要一个单例模式。"
随着学习的进程中集人员的心智开始能够分辨何时需要模式,何时不需要。中级人员的心智依然会企图把过多的模式套用在不适当的地方。但他们也开始察觉到有些模式并不适合目前的情况,可以对其改编使其合适。
悟道者的心智:"或许这里使用装饰者模式相当自然。"
悟道者的心智能够看到模式在何处能够自然融入,并不急切于使用模式,而是致力于能解决问题的简单方案。布道者会考虑对象的原则以及他们之间的折中。当对模式的需要自然出现时,悟道者的心智就拿捏得宜地采用模式。悟道者的心智能看到相似模式之间的关系以及他们在一图上的微妙差异.悟道者的心智也同于初学者的心智--不会让这些模式的知识过度影响设计的决策。
感谢:
《javascript设计模式与开发实践》--- byAlloy Team
https://book.douban.com/subject/26382780/
Pro JavaScript Design Patterns ---by ROSS HARMES&DUSTIN DIAZ
https://book.douban.com/subject/2227486/
Learning JavaScript Design Patterns -- by Addy Osmani
https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
A JavaScript Module Pattern-- by YUI Team
https://yuiblog.com/blog/2007/06/12/module-pattern/
What is so bad about singletons?
https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons




原创粉丝点击