职责连模式:
ChainOfResponsibility:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
优点:
请求是沿链传递至有一个ConcreteHandler对象处理它
但要注意链尾是否能处理所有请求
Demo1:
//处理请求的接口
abstract class Handler
{
protected Handler successor;
public void SetSuccessor(Handler successor)//设置继任者
{
this.successor = successor;
}
//处理请求的抽象方法
public abstract void HandlerRequest(int request);
}
// 有权处理0-10之间
class ConcreteHandler1:Handler
{
public override voidHandlerRequest(int request)
{
if (request >= 0 && request < 10)
{
Console.WriteLine("{0}处理请求{1}",
this.GetType().Name,request);
}
else if (successor != null)
{
successor.HandlerRequest(request);//转移到下一位
}
}
}
// 有权处理10-20之间
class ConcreteHandler2 : Handler
{
public override void HandlerRequest(int request)
{
if (request >= 10&& request < 20)
{
Console.WriteLine("{0}处理请求{1}",
this.GetType().Name,request);
}
else if (successor != null)
{
successor.HandlerRequest(request);//转移到下一位
}
}
}
。。。。。。
static void Main(string[]args)
{
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);
int[] request = { 2,3,12,14,3,28};
foreach (int i in request)
{
h1.HandlerRequest(i);
}
Console.ReadKey();
}