TS 设计模式-建造者、原型、单例

19 阅读1分钟

建造者模式

这个是为了解决 clean code 中参数超过三个的问题,建造者模式可以让我们分步骤构建。

但我除了看 Java 有使用过之外,还没见过哪个脑子正常的使用过。这个至少犯一个重复自己的问题。就不做介绍了。

原型模式

实现了 clone 接口,可以快速的复制一个对象。

interface Copyable<Self> {
  clone: () => Self
}

class Student implements Copyable<Student> {
  #name: string
  constructor(name: string) {
    this.#name = name
  }

  clone() {
    return new Student(this.#name)
  }
}

但是在 JS 中一般对象都是单独存在的,那么这个时候我们实现一个 deepClone 方法也是原型模式的体现。

这个 deepClone 就是一个图的复制,想写完善还是挺复杂的。

单例

  1. 直接使用全局变量,使用 es6 的 export 和 import(这个方式应该是更推荐的,React 有很多状态管理库用的就是这一套方案)
  2. 使用正规的单例写法
class Singleton {
  static #instance: Singleton
  private constructor() {}
  static getInstance() {
    if (!this.#instance) this.#instance = new Singleton()
    return this.#instance
  }
}