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
<<: 使用Lucene.Net达成全文检索!基础解说(二)
>>: 【C#】Behavioral Patterns Memento Mode
昨天分享介绍国外线上服务思考用户的数位防身术设计方式,今天就回到国内来看看目前国内线上服务实作,分析...
作为一名 IT,和日志打交道是必不可少的,我们经常需要去查看一些日志文件,以从中获取一些有用的信息,...
资料扩增 我们组的资料扩增这部分,因为第一次比赛,这个方法效果没有到非常好,采取的是用mask的方式...
Producer是讯息发送方, 他会对nsqd发送讯息, nsqd支援TCP(port:4150) ...
你有没有遇过网路出问题时,得到的讯息是丢锅叫你问问你的 ISP 呢?这个背锅的人究竟是谁? ISP,...