ChainOfResponsibility责任链模式(行为型)
作用:
责任链模式由一条链上的各个对象组成,每个对象可以处理自己范围内的请求,超出自己处理范围的发送到链上的上一个对象处理。在链的末端是默认的处理对象或是异常。
Role
The Chain of Responsibility pattern works with a list of Handler objects that have limitations on the nature of the requests they can deal with. If an object cannot handle a request, it passes it on to the next object in the chain. At the end of the chain,there can be either default or exceptional behavior.
设计:
IHandler 责任接口;
Handler1, Handler2,实现接口的各问题处理类;
Successor,下一个问题处理类
举例:
IHandler,接受贷款申请
Handler1,1万以内
Handler2,2万以内
Handler3,3万以内
DefaultHandler,超出3万报上级银行或拒绝申请
Successor,每个Handler的上级
实现:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChainOfResponsibility
{
class Handler
{
Handler next;
int id;
public int Limit {get; set;}
public Handler (int id, Handler handler)
{
this.id = id;
Limit = id*1000;
next = handler;
}
public string HandleRequest(int data)
{
if (data < Limit)
return "Request for " +data+" handled at level "+id;
else if (next!=null)
return next.HandleRequest(data);
else return ("Request for " +data+" handled BY DEFAULT at level "+id);
}
}
class ProgramHandler
{
enum Levels { Manager, Supervisor, Clerk }
static void Main(string[] args)
{
Handler start = null;
for (int i=5; i>0; i--) {
Console.WriteLine("Handler "+i+" deals up to a limit of "+i*1000);
start = new Handler(i, start);
}
int [] a = {50,2000,1500,10000,175,4500};
foreach (int i in a)
Console.WriteLine(start.HandleRequest(i));
Levels me = Levels.Manager;
Console.WriteLine(me);
Console.ReadLine();
}
}
}
应用场景:
对于请求有多个接受处理对象
在责任链上,每个对象都有固定的方式和规范将请求传递给上一个对象
对象是动态变化的
需要灵活的分配请求方式
Use the Chain of Responsibility pattern when…
You have:
• More than one handler for a request
• Reasons why a handler should pass a request on to another one in the chain
• A set of handlers that varies dynamically
You want to:
• Retain flexibility in assigning requests to handlers
总结:
将多个处理请求的责任对象串在一条链上,在这条链上将请求传递到正确的处理对象,从而避免请求的请求者和处理者之间的耦合关系。 如果一个请求的处理可能由不同责任对象完成,希望能自定义这个处理流程并且不希望直接和多个责任对象发生耦合的时候可以考虑责任链模式。另外,如果对一个请求的处理存在一个流程,需要经历不同的责任对象进行处理,并且这个流程比较复杂或只希望对外公开一个处理请求的入口点的话可以考虑责任链模式。其实,责任链模式还可以在构架的层次进行应用,比如.NET中的层次异常处理关系就可以看作是一种责任链模式。