專案初期:Status 欄位(Not Started / In Progress / Done...)狀態變更觸發不同郵件通知,單純 if-else 足矣。隨需求增長(新增狀態、多欄位聯動),ItemUpdating 膨脹成數百行條件判斷,維護極度困難。
經典適用場景:物件行為隨內部狀態改變而改變,且狀態在運行時切換。SharePoint 列表項目狀態機制完美吻合。
public abstract class State
{
public abstract void Select();
}
class InProgressState : State
{
public StateContext Context { get; set; }
public override void Select() => SendEmail(mgr);
}
class AheadOfScheduleState : State
{
public override void Select() => SendEmail(director);
}
// ... 其他狀態
class StateContext
{
private State _currentState;
private string _currentValue;
public StateContext(string currentValue) { _currentValue = currentValue; }
public void Process()
{
switch (_currentValue)
{
case "In Progress":
_currentState = new InProgressState(); break;
case "Ahead of Schedule":
_currentState = new AheadOfScheduleState(); break;
default: return;
}
_currentState.Select();
}
}
public override void ItemUpdating(SPItemEventProperties properties)
{
string currentStatus = properties.AfterProperties["Status"] as string;
new StateContext(currentStatus).Process();
}
雖未完全抽象化(Context 仍有 switch),但較原始 if-else 鏈大幅改善。後續可引入狀態轉換表或策略模式進一步解耦。