常见的 23 种的设计模式 - 1. 工厂方法模式(Factory Method Pattern)

85 阅读1分钟

上一篇:目录

下一篇:2. 抽象工厂模式(Abstract Factory Pattern)

假设我们有一个电脑类,它有两个属性:品牌和型号。我们想通过工厂方法来创建不同品牌和型号的电脑实例,而不是直接在代码中写 new Computer()

首先,我们定义电脑类和电脑工厂类:

class Computer {
  constructor(public brand: string, public model: string) {}
}

class ComputerFactory {
  createComputer(brand: string, model: string): Computer {
    return new Computer(brand, model);
  }
}

然后我们可以使用电脑工厂类来创建电脑实例:

const factory = new ComputerFactory();

const macbook = factory.createComputer('Apple', 'Macbook Pro');

console.log(macbook.brand, macbook.model); // Apple Macbook Pro

const thinkpad = factory.createComputer('Lenovo', 'ThinkPad X1 Carbon');

console.log(thinkpad.brand, thinkpad.model); // Lenovo ThinkPad X1 Carbon

这样我们就通过工厂方法来创建了不同品牌和型号的电脑实例,而且可以方便地在工厂类中进行修改和扩展。