最近在学习设计模式,又正好刚上手了typescript,就想要用ts实现一下试试。
懒汉单例模式
class PeopleSingle {
/**核心 - 一个接收实例的静态成员 */
private static people: PeopleSingle;
private name: string;
/**核心 - 私有构造函数 */
private constructor(name: string) {
this.name = name;
}
/**核心 - 获取实例 */
public static getInstance(): PeopleSingle {
if (this.people == null) {
this.people = new PeopleSingle('金闪闪');
}
return PeopleSingle.people;
}
public say(): void {
console.log(`I'm ${this.name}.`);
}
}
let people = PeopleSingle.getInstance();
people.say();
饿汉单例模式
class PeopleSingle {
/**核心 - 一个接收实例的静态成员,直接创建好实例 */
private static people: PeopleSingle = new PeopleSingle('金闪闪');
private name: string;
/**核心 - 私有构造函数 */
private constructor(name: string) {
this.name = name;
}
/**核心 - 获取实例 */
public static getInstance(): PeopleSingle {
return PeopleSingle.people;
}
public say(): void {
console.log(`I'm ${this.name}.`);
}
}
let people = PeopleSingle.getInstance();
people.say();