为什么要使用单例?
一个类只允许创建一个对象(或者实例),那这个类就是一个单例类,这种设计模式就叫作单例设计模式,简称单例模式。
场景一:表示全局唯一类
从业务概念上,如果有限数据在系统中只因存在一份,那么就比较适合为单例类。
比如,配置信息类。在系统中,我们只有一个配置文件,当配置文件被加载到内存后,以对象的形式存在,也理所应当只有一份。
如何实现一个单例
1. 饿汉式
在类加载的时候,instance 静态实例就已经创建并初始化好了,所以,instance 实例的创建过程是线程安全的。
class IdGenerator {
private id: number = 0;
private static instance: IdGenerator = new IdGenerator();
private constructor() {}
public static getInstance(): IdGenerator {
return IdGenerator.instance;
}
public getId(): number {
return ++this.id; Ï
}
}
// 使用
const idGenerator = IdGenerator.getInstance();
console.log(idGenerator.getId());
console.log(idGenerator.getId());
2.懒汉式
class IdGenerator {
private id: number = 0;
private static instance: IdGenerator | null = null;
private constructor() {}
public static getInstance(): IdGenerator {
if (this.instance === null) {
this.instance = new IdGenerator();
}
return this.instance;
}
public getId(): number {
return ++this.id;
}
}
// 使用
const idGenerator = IdGenerator.getInstance();
console.log(idGenerator.getId());
console.log(idGenerator.getId());