iT邦幫忙

0

【C#】Behavioral Patterns Chain of Responsibility Mode

c#
  • 分享至 

  • xImage
  •  

The Chain of Responsibility design pattern avoids coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. This pattern chains the receiving objects and passes the request along the chain until an object handles it.


責任鏈設計模式通過為多個對象提供處理請求的機會,避免將請求的發送者與其接收者耦合~ 此模式鏈接接收對象沿鏈傳遞請求,直到對象處理它~ 有點像是自製版的Switch Case~


學習目標: 責任鏈模式的概念及實務

學習難度: ☆☆☆


using System;

namespace ConsoleApp1
{
    public abstract class Handler
    {
        protected Handler NextHandler;

        public void SetNextHandler(Handler nexthandler)
        {
            this.NextHandler = nexthandler;
        }

        public abstract void HandleRequest(string country);
    }

    public class ConcreteHandler1 : Handler
    {
        public override void HandleRequest(string country)
        {
            if (country == "Russia")
            {
                Console.WriteLine("Russia is Europe country");
            }
            else if (country == "Germany")
            {
                Console.WriteLine("Germany is Europe country");
            }
            else if (NextHandler != null)
            {
                NextHandler.HandleRequest(country);
            }
        }
    }

    public class ConcreteHandler2 : Handler
    {
        public override void HandleRequest(string country)
        {
            if (country == "Taiwan")
            {
                Console.WriteLine("Taiwan is Asia country");
            }
            else if (country == "China")
            {
                Console.WriteLine("China is Asia country");
            }
            else if (NextHandler != null)
            {
                NextHandler.HandleRequest(country);
            }
            else
            {
                Console.WriteLine("Not found..");
            }
        }
    }

    public class MainProgram
    {
        public static void Main(string[] args)
        {
            Handler h1 = new ConcreteHandler1();

            Handler h2 = new ConcreteHandler2();

            h1.SetNextHandler(h2); //有點像指向的概念...

            string[] countries = { "Taiwan", "Russia", "China", "Russia" };

            foreach (string country in countries)
            {
                h1.HandleRequest(country); //要求判斷...
            }
        }
    }
}

參考資料:

https://www.dofactory.com/net/chain-of-responsibility-design-pattern


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言