Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8e478a6

Browse files
committed
Added files via upload
1 parent 980af3b commit 8e478a6

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

singleton/singleton.js

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
//1.最简单的实现方法
2+
var Singleton = function(name){
3+
this.name = name;
4+
this.instance = null;
5+
};
6+
7+
Singleton.prototype.getName = function(){
8+
alert(this.name);
9+
};
10+
11+
Singleton.getInstance = function(name){
12+
if(!this.instance){
13+
this.instance = new Singleton();
14+
}
15+
return this.instance;
16+
};
17+
18+
var a = Singleton.getInstance('seven1');
19+
var b = Singleton.getInstance('seven2');
20+
alert(a === b); // true
21+
22+
//或者
23+
var Singleton = function(name){
24+
this.name = name;
25+
}
26+
27+
Singleton.prototype.getName = function(){
28+
alert(this.name);
29+
}
30+
31+
Singleton.getInstance = (function(){
32+
var instance = null;
33+
return function(name){
34+
if(!instance){
35+
instance = new Singleton('name');
36+
}
37+
return instance;
38+
}
39+
})();
40+
41+
var a = Singleton.getInstance('seven1');
42+
var b = Singleton.getInstance('seven2');
43+
alert(a === b); // true
44+
45+
//2.透明的单例模式。上述简单的单例模式并不透明,必须要知道Singleton对象有getInstance方法可以创造单例,并不能直接new
46+
//下面代码负责在页面中创建唯一的div节点
47+
var CreatDiv = (function(){
48+
var instance;
49+
var CreatDiv = function(html){
50+
if(instance){
51+
return instance;
52+
}
53+
this.html = html;
54+
this.init();
55+
return instance = this;
56+
};
57+
58+
CreatDiv.prototype.init = function(){
59+
var div = document.createElement('div');
60+
div.innerHTML = this.html;
61+
document.body.appendChild(div);
62+
};
63+
return CreatDiv;
64+
})();
65+
66+
var a = new CreatDiv('seven1');
67+
var b = new CreatDiv('seven2');
68+
69+
alert(a === b); //true
70+
71+
//虽然上述例子实现了单例透明,但是singleton构造函数没有做到职责单一,一个方法干了两件事情,第一,是创建对象和
72+
//执行初始化init方法,第二是保证只有一个对象
73+
//用代理模式实现单例模式可解决此问题
74+
var CreatDiv = function(html){
75+
this.html = html;
76+
this.init();
77+
};
78+
79+
CreatDiv.prototype.init = function(){
80+
var div = document.createElement('div');
81+
div.innerHTML = this.html;
82+
document.body.appendChild(div);
83+
};
84+
85+
//接下来引入代理类ProxySingetonCreateDiv
86+
var ProxySingetonCreateDiv = (function(){
87+
var instance;
88+
return function(){
89+
if(!instance){
90+
instance = new CreatDiv(html);
91+
}
92+
return instance;
93+
}
94+
})();
95+
96+
var a = new ProxySingetonCreateDiv('seven1');
97+
var b = new ProxySingetonCreateDiv('seven2');
98+
99+
alert(a === b);

0 commit comments

Comments
 (0)