js 设计模式 ----- 单体模式(一)基本概念
1》单体模式
理解:单体模式是提供了一种代码组织为一个逻辑单元的手段,这个逻辑单元中的代码可以通过单一变量进行访问。
优点:
a)可以划分命名空间(a对象的str和b对象的str)
b)使代码阅读性,维护性更好
c)可以实例化(new),但是只能实例化一次
第一种写法:
function Obj(){
this.name = "张三";
this.run = null;
}
Obj.prototype.getName = function(){
return this.name;
};
function getRun(){
//可以实例化(new),但是只能实例化一次
if(!this.run){
this.run = new Obj();
}
return this.run;
}
var a = getRun();
var b = getRun();
console.log(a.name);//张三
console.log(b.name);//张三
console.log(a===b);//true
第二种写法:(匿名函数自我执行)
function Obj(){
this.name = "张三";
}
Obj.prototype.getName = function(){
return this.name;
};
var getRun = (function(){
var run = null;
return function(){
if(!run){
run = new Obj();
}
return run;
}
})();
var a = getRun();
var b = getRun();
console.log(a.name);//张三
console.log(b.name);//张三
console.log(a===b);//true