隨著業務增長,GetOrder 方法裡的 if (cond1) ... if (cond2) ... if (cond3) ... 越寫越長、越難維護。本文提出 Pipeline(管線/流水線)模式:將每個條件判斷與處理邏輯封裝成獨立 IHandle<T>,串成列表依序執行。新增/調整/測試分支皆互不干擾,完美符合開放封閉原則。
Order GetOrder(string orderNo) {
var order = repo.GetOrder(orderNo);
if (order.Condition1) { /* ... */ }
if (order.Condition2) { /* ... */ }
if (order.Condition3) { /* ... */ }
// 業務增長 → 繼續加 if,方法膨脹到 200 行
}
// 1. 處理器介面
public interface IHandle<T> {
void Process(T entity);
}
// 2. 具體處理器(各自只管一件事)
public class Condition1Handler : IHandle<Order> {
public void Process(Order o) {
if (!o.IsPaid) Console.WriteLine("你還沒付錢");
}
}
public class Condition2Handler : IHandle<Order> { /* ... */ }
// 3. 管線協調器
public class Pipeline<T> {
private readonly List<IHandle<T>> _handles = new();
private T _entity;
public void AddEntity(T entity) => _entity = entity;
public void AddHandler(IHandle<T> h) => _handles.Add(h);
public void Process() {
foreach (var h in _handles) h.Process(_entity);
}
}
// 4. 使用端
var pipeline = new Pipeline<Order>();
pipeline.AddEntity(order);
pipeline.AddHandler(new Condition1Handler());
pipeline.AddHandler(new Condition2Handler());
pipeline.Process();

同一個 Pipeline<T> 可處理 Order、Product 等任意型別,只需實作對應的 IHandle<T>。
Process 回傳 bool,false 時停止後續處理器。Task ProcessAsync(T),配合 await 串接 I/O 密集型處理器。IEnumerable<IHandle<Order>> 注入建構函式,自動掃描註冊的處理器。| 模式 | 核心意圖 | 關鍵差異 |
|---|---|---|
| Pipeline | 依序執行多個處理器,皆可存取同一實體 | 無「傳遞給下一個」概念,全跑完 |
| Chain of Responsibility | 處理器決定是否處理並傳遞給下一個 | 可中斷、可修改請求物件 |
| Strategy | 選擇「一個」演算法執行 | 單一執行、可動態切換 |
管線模式不是銀彈,但對「單一實體、多階段驗證/轉換/副作用」的場景極度對味。下次看到 if-else 連環砲,試著拆成 IHandle 丟進 Pipeline——你的未來維護者會感謝你。