Skip to content

工厂设计模式 / Factory

工厂设计模式提供了一种创建对象而不必明确指定类的方法。该模式将对象的创建逻辑封装到工厂方法中,允许对象创建者和要创建的对象之间的灵活性和解耦。

Code

javascript
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}

class CarFactory {
  createCar(make, model) {
    return new Car(make, model); // 返回一个新的Car实例
  }
}