Skip to content

创建型模式

创建型设计模式。

单例模式

确保一个类只有一个实例。

javascript
class Singleton {
  constructor() {
    if (Singleton.instance) {
      return Singleton.instance
    }
    Singleton.instance = this
  }
}

工厂模式

创建对象而不指定具体的类。

javascript
class Factory {
  createProduct(type) {
    switch(type) {
      case 'A': return new ProductA()
      case 'B': return new ProductB()
    }
  }
}

建造者模式

将复杂对象的构建与表示分离,允许分步配置、按需返回不同表示。

javascript
class ComputerBuilder {
  setCpu(cpu) { this.cpu = cpu; return this }
  setRam(ram) { this.ram = ram; return this }
  build() { return { cpu: this.cpu, ram: this.ram } }
}

const pc = new ComputerBuilder().setCpu('i9').setRam('32G').build()

原型模式

通过克隆已有实例(原型)创建新对象,避免重复初始化开销。

javascript
class Prototype {
  clone() { return Object.assign(Object.create(Object.getPrototypeOf(this)), this) }
}