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

C# 設計模式:責任鏈模式主管與經理處理者實作 (4/5)

     編輯:關於C語言

具體處理者:Leader (主管)

處理長度 5-9 字元的訊息,否則傳遞給上級:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.ChainOfResponsibility
{
    /// 
    /// 抽象處理者(Handler)角色
    /// 
    public class Leader : AbstractExecutor
    {
        /// 
        /// 插入 Message
        /// 
        /// Message 實體物件
        /// 執行者;內容;時間
        public override string Insert(MessageModel mm)
        {
            string rtn = "";

            // 插入的信息字符數小於 10
            if (mm.Message.Length < 10)
            {
                SqlMessage m = new SqlMessage();

                if (m.Insert(mm))
                {
                    rtn = "執行者:主管" + " 內容:" + mm.Message + " 時間:" + mm.PublishTime.ToString();
                }
            }
            // 否則讓上級去執行
            else if (base._executor != null)
            {
                rtn = _executor.Insert(mm);
            }

            return rtn;
        }
    }
}

具體處理者:Manager (經理)

處理長度 10-14 字元的訊息,超出則拒絕:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.ChainOfResponsibility
{
    /// 
    /// 抽象處理者(Handler)角色
    /// 
    public class Manager : AbstractExecutor
    {
        /// 
        /// 插入 Message
        /// 
        /// Message 實體物件
        /// 執行者;內容;時間
        public override string Insert(MessageModel mm)
        {
            string rtn = "";

            // 插入的信息字符數小於 15
            if (mm.Message.Length < 15)
            {
                SqlMessage m = new SqlMessage();

                if (m.Insert(mm))
                {
                    rtn = "執行者:經理" + " 內容:" + mm.Message + " 時間:" + mm.PublishTime.ToString();
                }
            }
            else
            {
                rtn = "你所插入的Message不符合要求";
            }

            return rtn;
        }
    }
}

處理者鏈結邏輯圖解

Client → Employee (長度<5) 
              │
              ├─ 滿足條件 → 執行 SqlMessage.Insert → 返回結果
              │
              └─ 不滿足 → _executor.Insert() → Leader (長度<10)
                                    │
                                    ├─ 滿足條件 → 執行 → 返回
                                    │
                                    └─ 不滿足 → _executor.Insert() → Manager (長度<15)
                                                              │
                                                              ├─ 滿足條件 → 執行 → 返回
                                                              │
                                                              └─ 不滿足 → 返回拒絕訊息

關鍵設計點

  • 條件判斷:每個處理者定義各自處理範圍(長度閾值)。
  • 鏈結傳遞:不滿足條件且有上級(_executor != null)時委派給 _executor.Insert()。
  • 終端處理:經理為鏈尾,超出範圍直接返回拒絕,不再傳遞。
  • 實際執行委派:最終由 SqlMessage 執行真實插入操作。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved