qiuhongbingo / blog

Writing something in Issues.
https://github.com/qiuhongbingo/blog/issues
3 stars 0 forks source link

建造者模式在前端中的应用 #24

Open qiuhongbingo opened 4 years ago

qiuhongbingo commented 4 years ago
/**
 * 建造者的精髓在于“分步骤分情况构建一个复杂的对象”
 * 先看一个分情况的例子
 */
class Car {
  constructor(options) {
    const { doors = 4, state = 'new', color = 'black' } = options
    this.doors = doors
    this.state = state
    this.color = color
  }
}

class Truck {
  constructor(options) {
    const { wheelSize = 'medium', state = 'used', color = 'silver' } = options
    this.wheelSize = wheelSize
    this.state = state
    this.color = color
  }
}

class VehicleFactory {
  createVehicle(options) {
    switch (options.type) {
      case 'car':
        this.vehicleTarget = Car
        break
      case 'truck':
        this.vehicleTarget = Truck
        break
      default:
        this.vehicleTarget = Car
        break
    }
    return new this.vehicleTarget(options)
  }
}

let factory = new VehicleFactory()

let instance1 = factory.createVehicle({
  type: 'car',
  color: 'yellow',
  doors: 4
})

let instance2 = factory.createVehicle({
  type: 'truck',
  state: 'new',
  wheelSize: 'small'
})

instance1 instanceof Car // true
instance2 instanceof Truck // true

/**
 * 再来一个分步骤的例子
 * 例如构建一个 pizza 需要在初始化时传入需要的参数,参数一旦变多就会非常失控
 */
class Pizza {
  constructor(size, mushroom = true, oliver = true, poulet = false, chesse = true, tomato = false, lettuce = false) {}
}

// 这种时候就可以使用建造者模式
class Pizza {
  constructor(size) {
    this.size = size
  }

  addMushroom() {
    this.mushroom = true
    return this
  }

  addOliver() {
    this.oliver = true
    return this
  }

  addPoulet() {
    this.poulet = true
    return this
  }

  addChesse() {
    this.chesse = true
    return this
  }

  addTomato() {
    this.tomato = true
    return this
  }

  addLettuce() {
    this.lettuce = true
    return this
  }

  build() {
    return new Pizza(this)
  }
}

new Pizza(32)
  .addOliver()
  .addTomato()
  .build()