前言
责任链模式通过将请求和处理者解耦,关联多个处理者形成一个链条,使每个处理者都有机会处理请求,避免了将所有处理逻辑集中在一个对象中的复杂性。
代码
csharp
//请求者
public class Requestor
{
private string content;
public string Content { get { return content; } }
public Requestor(string content)
{
this.content = content;
}
}
//处理者
public abstract class Handler
{
public abstract void SetNext(Handler handler);
public abstract void HandleRequest(Requestor requestor);
}
//处理者:接收者A
public class ReceiverA : Handler
{
private Handler nextHandler;
public override void SetNext(Handler handler)
{
nextHandler = handler;
}
public override void HandleRequest(Requestor requestor)
{
if (requestor.Content.Equals("A"))
{
Console.WriteLine("receiverA handle the request...");
}
else if(nextHandler!=null)
{
nextHandler.HandleRequest(requestor);
}
}
}
//处理者:接收者B
public class ReceiverB : Handler
{
private Handler nextHandler;
public override void HandleRequest(Requestor requestor)
{
if (requestor.Content.Equals("B"))
{
Console.WriteLine("receiverB hanlde the request...");
}else if (nextHandler != null)
{
nextHandler.HandleRequest(requestor);
}
}
public override void SetNext(Handler handler)
{
this.nextHandler = handler;
}
}
/*
* 行为型模式:Behavioral Pattern
* 责任链模式: Chain-of-responsibility Pattern
*/
internal class Program
{
static void Main(string[] args)
{
//创建接收请求
Handler handlerA = new ReceiverA();
Handler handlerB = new ReceiverB();
//设置下一个请求处理者
handlerA.SetNext(handlerB);
//创建请求者A,并处理请求
Requestor receiverA = new Requestor("A");
handlerA.HandleRequest(receiverA);
Requestor receiverB = new Requestor("B");
handlerA.HandleRequest(receiverB);
Requestor requestorC = new Requestor("C");
handlerA.HandleRequest(requestorC);
Requestor receiverA2 = new Requestor("A");
handlerA.HandleRequest(receiverA2);
Console.ReadLine();
}
}