cover

Mediator 模式:互動集中管理

Mediator 模式讓物件不直接彼此呼叫,而是透過中介者協調,降低耦合。

classDiagram
    class OrderMediator {
        -inventory : Inventory
        -payment : Payment
        -shipping : Shipping
        +processOrder(order) Result
    }
    class Inventory {
        +check(items) boolean
    }
    class Payment {
        +process(amount) boolean
    }
    class Shipping {
        +arrange(address) void
    }
    OrderMediator --> Inventory
    OrderMediator --> Payment
    OrderMediator --> Shipping
    note for OrderMediator "協調各模組互動\n模組間不直接通訊"

使用情境

  1. 訂單管理:庫存、付款、配送協調。
  2. 聊天室:統一傳送訊息給多位使用者。
  3. UI 互動:表單欄位間的依賴關係。

實作範例

Mediator 模式:中介者協調多個部門

class OrderMediator {
  constructor() {
    this.inventory = new Inventory();
    this.payment = new Payment();
    this.shipping = new Shipping();
  }
 
  async processOrder(order) {
    const stockOk = await this.inventory.check(order.items);
    if (!stockOk) {
      return { success: false, message: 'Out of stock' };
    }
 
    const paymentOk = await this.payment.process(order.amount);
    if (!paymentOk) {
      return { success: false, message: 'Payment failed' };
    }
 
    await this.shipping.arrange(order.address);
    return { success: true, message: 'Order completed' };
  }
}
 
class Inventory {
  async check(items) {
    console.log('Checking inventory for items:', items);
    return true;
  }
}
 
class Payment {
  async process(amount) {
    console.log('Processing payment:', amount);
    return true;
  }
}
 
class Shipping {
  async arrange(address) {
    console.log('Arranging shipping to:', address);
  }
}
 
const mediator = new OrderMediator();
const order = {
  items: ['item1', 'item2'],
  amount: 199.99,
  address: '台北市信義區',
};
 
mediator.processOrder(order).then(result => {
  console.log(result);
});

優點

  • 物件間耦合降低
  • 協調邏輯集中管理
  • 對象可獨立復用

缺點

  • 中介者可能過於龐大

延伸閱讀