Skip to content

构造者模式 / Builder

在该设计模式中,Builder 提供了一些方法,用于配置要创建的对象的属性。

Code

javascript
class CarBuilder {
  constructor() {
    this.car = new Car();
  }
  setMake(make) {
    // 为要创建的对象实例属性赋值,并返回 Builder 实例以进行链式调用
    this.car.make = make;
    return this;
  }
  setEngine(engine) {
    this.car.engine = engine;
    return this;
  }
  // 返回对象实例
  build() {
    return this.car;
  }
}

class Car {
  constructor() {
    this.engine = '';
    this.make = '';
  }
  display() {
    return `My engine is ${this.engine}, my make is ${this.make}`;
  }
}

const carBuilder = new CarBuilder();
const car = carBuilder.setMake('mi').setEngine('v2').build();
car.display();
// 输出:My engine is v2, my make is mi