【C#】Behavioral Patterns Chain of Responsibility Mode

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


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章