Skip to content

Commit 5061489

Browse files
committed
Create singleton.js
添加设计模式例子。
1 parent baf75f8 commit 5061489

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

singleton.js

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/**
2+
* @file 单例模式
3+
* @author tuanfe
4+
* @date 2014/5/19
5+
*/
6+
7+
8+
/**
9+
* 实现方式一:定义一个字面量的形式创建一个对象,就可以认为是一个单体
10+
*/
11+
12+
var singleton = {
13+
name: 'tuanfe',
14+
age: 25,
15+
height: 175
16+
}
17+
18+
/**
19+
* 实现方式二:构造函数的方式
20+
*
21+
*/
22+
23+
function Singleton(){
24+
//正常的属性
25+
this.name= 'tuanfe';
26+
this.age= 25;
27+
28+
if(typeof Singleton.instance === "object"){
29+
return Singleton.instance;
30+
}
31+
32+
//缓存this
33+
Singleton.instance = this;
34+
35+
return this;
36+
}
37+
38+
var s1 = new Singleton();
39+
var s2 = new Singleton();
40+
console.log(s1 === s2); //true
41+
42+
/**
43+
* 实现方式三: 立即执行函数方式
44+
*
45+
*/
46+
47+
var Singleton;
48+
(function(){
49+
var instance;
50+
Singleton = function Singleton(){
51+
if(instance){
52+
return instance;
53+
}
54+
55+
instance = this;
56+
//正常的属性
57+
this.name= 'tuanfe';
58+
this.age= 25;
59+
}
60+
})();
61+
62+
var s1 = new Singleton();
63+
var s2 = new Singleton();
64+
console.log(s1 === s2); //true
65+
66+
/**
67+
* 实现方式四:闭包
68+
*
69+
*/
70+
71+
var Singleton = (function(){
72+
//实例引用
73+
var instance;
74+
function init(){
75+
//对象初始化操作
76+
}
77+
78+
return {
79+
//暴露出公共API,提供全局唯一访问点
80+
getInstance: function(){
81+
if(!instance){
82+
instance = init();
83+
}
84+
return instance;
85+
}
86+
}
87+
})();
88+
89+
var s1 = Singleton.getInstance();
90+
var s2 = Singleton.getInstance();
91+
console.log(s1 ===s2); //true
92+

0 commit comments

Comments
 (0)