责任链模式(Chain of Responsibility Pattern)中包含了一些命令对象和一系列的处理对象。 每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。 该模式还描述了往该处理链的末尾添加新的处理对象的方法。
下面是责任链模式的一个简单示例:
package 责任链模式;
//请求对象,本例只是简单地包含一个请求级别
public class Request {
private int level=0;
public Request(int level){
this.level=level;
}
public int getLevel(){
return this.level;
}
}
package 责任链模式;
//每一个Handler类对象首先决定是否需要在该层做处理,然后将控制传递到下一个Handler。
public abstract class Handler {
int level=0;//用来判断请示的级别,实际项目中可能会更复杂
Handler nextHandler=null;
public Handler(int level){
this.level=level;
}
public final void handleRequest(Request request){
if(request.getLevel()==this.level){
response(request);
} else {
if(nextHandler!=null){
nextHandler.handleRequest(request);
}else{
System.out.println("超出所能处理的级别!");
}
}
}
public void setNextHandler(Handler nextHandler){
this.nextHandler=nextHandler;
}
public abstract void response(Request request);
}
package 责任链模式;
public class ConcreteHandler extends Handler{
public ConcreteHandler(int level) {
super(level);
}
@Override
public void response(Request request) {
System.out.println("ConcreteHandler处理了"+request.getLevel()+"级请求");
}
}
package 责任链模式;
//客户端
public class Client {
public static void main(String[] args) {
Request request1=new Request(1);
Request request2=new Request(2);
Request request3=new Request(3);
Request request4=new Request(4);
ConcreteHandler handler1=new ConcreteHandler(1);
ConcreteHandler handler2=new ConcreteHandler(2);
ConcreteHandler handler3=new ConcreteHandler(3);
handler1.setNextHandler(handler2);
handler2.setNextHandler(handler3);
handler1.handleRequest(request1);
handler1.handleRequest(request2);
handler1.handleRequest(request3);
handler1.handleRequest(request4);
}
}
输出:
ConcreteHandler处理了1级请求
ConcreteHandler处理了2级请求
ConcreteHandler处理了3级请求
超出所能处理的级别!