责任链模式
//1.抽象的处理方法
public interface IHandler{
void handlerDo(Request req);//进行具体的处理
}
//2.具体的请求类
public class Request{
private int level;
private String content;
public Request(int level,String content){
this.level = level;
this.content = content;
}
public int getRequestLevel(){
return this.level;
}
public String getRequestContent(){
return this.content;
}
}
//3.具体的处理类
public Handler implement IHandler{
private IHandler next = null;
private int level;
public Handler(int level){
this.level = level;
}
public void setNext(IHandler next){
this.next = next;
}
//具体的对请求的处理
public void handlerDo(Request request){
if(this.level==request.getRequestLevel()){
System.out.println("等级为"+level+
"的处理者处理了等级为"
+getRequestLevel(request)+
"的请求,请求内容为"+
request.getRequestContent());
}else{
if(next!=null){
next.handlerDo(request);
}else{
System.out.println("系统没有找到合适的处理者");
}
}
}
}
//4.具体的调用内
public class Client{
public static void main(String[] args){
Request request = new Request(2,"请领导批准两万块钱的费用");
Handler handler1= new Handler(1);
Handler handler2= new Handler(2);
Handler handler3= new Handler(3);
handler1.setNext(handler2);
handler2.setNext(handler3);
handler3.setNext(null);
handler1.handlerDo(request);
}
}
网友评论