模式定义
职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
模式结构图
示例代码
class Program
{
static void Main(string[] args)
{
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandle2();
Handler h3 = new ConcreteHandle3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);
int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
foreach (var request in requests)
{
h1.HandleRequest(request);
}
}
}
public abstract class Handler
{
protected Handler successor;
public void SetSuccessor(Handler successor)
{
this.successor = successor;
}
public abstract void HandleRequest(int request);
}
public class ConcreteHandler1 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 0 && request < 10)
{
Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}
public class ConcreteHandle2 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 10 && request < 20)
{
Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}
public class ConcreteHandle3 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 20 && request < 30)
{
Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}