单例模式例子-国王与大臣

第一种写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function Minister(name) {//大臣
this.name=name;
}
Minister.prototype.say=function() {
console.log(this.name+"大王,冤枉啊!");
};
function Emperor() {//大王
this.name="大王";
this.id=Math.random();
// this.instance=null;

}
Emperor.prototype.say=function() {
console.log(this.name+this.id+"滚");
};
// Emperor.getInstance=function() {
// if(!this.instance){
// this.instance=new Emperor();
// }
// return this.instance;
// };
Emperor.getInstance=(function() {
var instance = null;//将instance私有化
return function() {
if(!instance) {//不存在即创建,否则返回
instance=new Emperor();
}
return instance;
}
})();
var minister1=new Minister("张三");
var emperor1=Emperor.getInstance();
var minister2 = new Minister("李四");
var emperor2=Emperor.getInstance();
var minister3 = new Minister("王二麻子");
var emperor3=Emperor.getInstance();
minister1.say();
emperor1.say();
minister2.say(); emperor2.say();
minister3.say(); emperor3.say();