cover

Builder 模式:把組裝流程拆開

Builder 模式把建立複雜物件的流程拆成多個步驟,讓你可以依需求組合不同配置。

classDiagram
    class ReportDirector {
        -builder : ReportBuilder
        +buildMonthlyReport() Report
    }
    class ReportBuilder {
        -report : Report
        +setTitle(title) ReportBuilder
        +addChart(chart) ReportBuilder
        +addTable(table) ReportBuilder
        +setNotes(notes) ReportBuilder
        +build() Report
    }
    class Report {
        -title : String
        -charts : Array
        -tables : Array
        -notes : String
    }
    ReportDirector --> ReportBuilder : 指揮建立流程
    ReportBuilder --> Report : 產出

使用情境

  1. 報告生成:標題、圖表、表格分步建立。
  2. UI 元件:複雜表單或卡片元件組裝。
  3. 文件輸出:PDF、Word 生成流程。

實作範例

Builder 模式:分步組裝報表

class Report {
  constructor() {
    this.title = '';
    this.charts = [];
    this.tables = [];
    this.notes = '';
  }
}
 
class ReportBuilder {
  constructor() {
    this.report = new Report();
  }
 
  setTitle(title) {
    this.report.title = title;
    return this;
  }
 
  addChart(chart) {
    this.report.charts.push(chart);
    return this;
  }
 
  addTable(table) {
    this.report.tables.push(table);
    return this;
  }
 
  setNotes(notes) {
    this.report.notes = notes;
    return this;
  }
 
  build() {
    return this.report;
  }
}
 
class ReportDirector {
  constructor(builder) {
    this.builder = builder;
  }
 
  buildMonthlyReport() {
    return this.builder
      .setTitle('Monthly Sales Report')
      .addChart({ type: 'bar', data: [100, 200, 150] })
      .addTable({ headers: ['Product', 'Sales'], rows: [] })
      .setNotes('Generated automatically')
      .build();
  }
}
 
const builder = new ReportBuilder();
const director = new ReportDirector(builder);
const monthlyReport = director.buildMonthlyReport();
console.log(monthlyReport);

優點

  • 建立流程清楚
  • 產品組合彈性高
  • 建立與表示分離

缺點

  • 類別數量增加

延伸閱讀