建造者模式使用示例

68 阅读1分钟

传送门

设计模式-建造者模式理解:shusheng007.top/2020/02/16/…

应用场景

构造一个button对象,涉及多个属性,包括必选属性和可选属性

代码示例

1.传统模式

// 传统模式
class ButtonProduct {
  static key
  static name
  static type // 可选
  static handler // 可选
  constructor({key, name, handler }) {
    this.key = key
    this.name = name
    this.type = 'text'
    this.handler = handler || undefined
  }
  build() {
    return {
      name: this.name,
      key: this.key,
      type: this.type ,
      action: {
        handler: this.handler
      }
    }
  }
}

const button = new ButtonProduct({key: 'create', name: '新增', handler: () => {console.log(111)}})
console.log(button.build())

// 打印结果
// {
//   name: '新增',
//   key: 'create',
//   type: 'text',
//   action: { handler: [Function: handler] }
// }

2.建造者模式

// 建造者模式
// 产品类 建造者基类
class ButtonProduct {
  static key
  static name
  static type // 可选
  static handler // 可选
  static buttonBuilder

  constructor(key, name, builder) {
    this.key = key
    this.name = name
    this.buttonBuilder = builder
  }
  setType(type) {
    this.type = type || 'button'
    return this
  }
  setHandler(handler) {
    this.handler = handler
    return this
  }
  build() {
    return this.buttonBuilder.build()
  }
}
class ButtonBuilder {
  static absButton //抽象button
  static builder (key, name) {
    const builder = new ButtonBuilder(key, name) // 实例化产品类用于链式调用
    return builder.absButton
  }
  constructor(key, name) {
    this.absButton = new ButtonProduct(key, name, this)
  }
  handler () {
    console.log('handler')
  }
  build() {
    return {
      name: this.absButton.name,
      key: this.absButton.key,
      type: this.absButton.type,
      action: {
        handler: this.handler.bind(this)
      }
    }
  }
}

const deleteButton = ButtonBuilder.builder('delete', '删除').setType('text').build()
console.log(deleteButton)

// 打印结果
// {
//   name: '删除',
//   key: 'delete',
//   type: 'text',
//   action: { handler: [Function: bound handler] }
// }