TypeScript实现设计模式——单例模式

前端开发 作者: 2024-08-20 03:50:01
最近在学习设计模式,又正好刚上手了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();
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_65305.html