飞雪连天射白鹿,笑书神侠倚碧鸳

0%

【23种设计模式】1单例模式

描述:一个类只有一个实例
优点:减少内存,共享访问
缺点:不宜扩展和测试

应用:用于需要频繁创建的对象


两种实现

classDiagram
    class Singleton {
        -constructor()
        -getInstance
        +getInstance()
    }
1
2
3
4
5
6
7
8
9
10
11
12
// 饿汉模式,类的实例在初始化时创建
class Singleton {
// 构造类私有化,外部不能new
private constructor(){}
// 类的内部,【立即】创建对象实例化
private static instance : Singleton = new Singleton();
// 公有的静态方法,返回实例对象
public static getInstance() : Singleton {
return this.instance;
}
}
console.log(Singleton.getInstance(), '11111');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 懒汉模式,类的实例在调用时创建
class Singleton {
// 构造类私有化,外部不能new
private constructor(){}
// 类的内部创建空对象
private static instance: Singleton = null;
// 公有的静态方法,【调用时】返回实例对象
public static getInstance() : Singleton {
if (this.instance === null) {
this.instance = new Singleton();
}
return this.instance;
}
}
console.log(Singleton.getInstance(), '2222')
听说,打赏我的人最后都找到了真爱
↘ 此处应有打赏 ↙
// 用户脚本