首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

SharePoint 開發累積:Event Handler 中導入 State 模式消除 if-else 地獄

     編輯:關於.NET

演變歷程

專案初期:Status 欄位(Not Started / In Progress / Done...)狀態變更觸發不同郵件通知,單純 if-else 足矣。隨需求增長(新增狀態、多欄位聯動),ItemUpdating 膨脹成數百行條件判斷,維護極度困難。

State 模式適用性分析

經典適用場景:物件行為隨內部狀態改變而改變,且狀態在運行時切換。SharePoint 列表項目狀態機制完美吻合。

重構實作

1. 抽象狀態基類

public abstract class State
{
    public abstract void Select();
}

2. 具體狀態類別

class InProgressState : State
{
    public StateContext Context { get; set; }
    public override void Select() => SendEmail(mgr);
}

class AheadOfScheduleState : State
{
    public override void Select() => SendEmail(director);
}
// ... 其他狀態

3. Context 管理狀態轉換

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();
    }
}

4. Event Handler 精簡調用

public override void ItemUpdating(SPItemEventProperties properties)
{
    string currentStatus = properties.AfterProperties["Status"] as string;
    new StateContext(currentStatus).Process();
}

效益總結

  • 開放封閉原則:新增狀態只需新增 State 類別,修改 Context switch,不動 Event Handler
  • 單一職責:每個狀態邏輯封裝在對應類別
  • 可測試性:狀態邏輯可獨立單元測試

雖未完全抽象化(Context 仍有 switch),但較原始 if-else 鏈大幅改善。後續可引入狀態轉換表或策略模式進一步解耦。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved