今晚月色真美

什么是单例模式?

保证一个类仅有一个实例,并提供一个访问它的全局访问点

用一个变量标志当前是否已经为某个类型创建过对象,如果是,则下次直接返回之前创建的对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var Singleton = function (name) {
this.name = name;
this.instance = null;
}

Singleton.prototype.getName = function () {
console.log(this.name);
}

Singleton.getInstance = function (name) {
if (!this.instance) {
this.instance = new Singleton(name);
}
return this.instance;
}

var a = Singleton.getInstance('Tony1');
var b = Singleton.getInstance('Tony2');

console.log(a === b); // true

通过 Singleton.getInstance来获取 Singleton 类的唯一对象,里边使用了 new 来获取,导致了这个类的“不透明性”。

本站总字数统计:49.8k

感谢您的浏览, 本站总访问量为 次 。
载入天数...载入时分秒...