【读书笔记】设计模式 - 单例模式
神马是单例模式?简单的讲,就是某个构造函数,有且仅有一个实例存在,无论你调用该构造函数来创建实例多少次,如:
function Class(){} //仅仅用来举例 var instance_01 = new Class(); var instance_02 = new Class(); console.log( instance_01===instance_02 ); //输出:true
我们知道,在javascript,当且仅当 instance_01 与 instance_02 指向的是 同一个实例对象,上述表达式才有可能输出为true,换言之,即:
如果instance_01 与 instance_02 指向的不是同一个实例对象,即使 instance_01 与 instance_02 拥有完全相同的属性值,上述表达式也会输出 false
可以做个小测试:
function Wife( name ){ this.name = name; } Wife.prototype.shout = function(){ console.log( 'i\'m your only wife '+ this.name +' , do remember !'); }; var wife_01 = new Wife( 'Marry' ); var wife_02 = new Wife( 'Mary' ); console.log( wife_01===wife_02 ); //尽管名字相同,但输出为:false,妻子竟然有两个,天~~
那么,最上面举的那个例子是怎么实现的呢?
最简单直观的思路:第一次调用该构造函数创建实例对象的时候,可以将该实例对象的引用保存下来,接下来,当该构造函数被再次调用,无论多少次,都只是返回之前保存的那个实例对象
还是用 妻子 那个例子:
function Wife( name ){ if( Wife.instance ){ return Wife.instance; } Wife.instance = this; this.name = name; } Wife.prototype.shout = function(){ console.log( 'i\'m your only wife '+ this.name +' , do remember !'); }; var wife_01 = new Wife( 'Marry' ); wife_01.shout(); //输出:i'm your only wife Marry , do remember ! var wife_02 = new Wife( 'Lucy' ); wife_02.shout(); //输出:i'm your only wife Marry , do remember ! console.log( wife_01===wife_02 ); //输出:true
很好,现在已经符合一夫一妻制的要求了,但总觉得有些不对劲——如果有人将 Wife.instance 恶意修改了,那不久悲剧了
针对于此,打个小补丁:
var Wife = (function(){ var instance = null; //外部无法直接访问,于是安全了 var _wife = function( name ){ if( instance ){ return instance; } instance = this; this.name = name; } return _wife; })(); Wife.prototype.shout = function(){ console.log( 'i\'m your only wife '+ this.name +' , do remember !'); }; var wife_01 = new Wife( 'Marry' ); wife_01.shout(); //输出:i'm your only wife Marry , do remember ! var wife_02 = new Wife( 'Lucy' ); wife_02.shout(); //输出:i'm your only wife Marry , do remember ! console.log( wife_01===wife_02 ); //输出:true
OVER
github博客:https://github.com/chyingp/blog
新浪微博:http://weibo.com/chyingp
站酷主页:http://www.zcool.com.cn/u/346408/