Java设计模式--责任链模式
2018-04-19 本文已影响0人
留给时光吧
该模式将多个接收者连成链,当请求来临时,沿着责任链匹配接受者,直到有对象接受为止,对请求者和接收者进行了充分的解耦。简单实现:
抽象类:
public abstract class Handler {
public Handler next;
public abstract void handleRequest(String condition);
public void setNext(Handler handler){
next = handler;
};
}
实现类
public class HandlerImpl1 extends Handler{
public static final String CONDITION = "HandlerImpl1";
@Override
public void handleRequest(String condition) {
if (CONDITION.equals(condition)){
System.out.println("HandlerImpl1 handle");
}else{
if(next != null)
next.handleRequest(condition);
}
}
}
public class HandlerImpl2 extends Handler{
public static final String CONDITION = "HandlerImpl2";
@Override
public void handleRequest(String condition) {
if (CONDITION.equals(condition)){
System.out.println("HandlerImpl2 handle");
}else{
if(next != null)
next.handleRequest(condition);
}
}
}
public class HandlerImpl3 extends Handler{
public static final String CONDITION = "HandlerImpl3";
@Override
public void handleRequest(String condition) {
if (CONDITION.equals(condition)){
System.out.println("HandlerImpl3 handle");
}else{
if(next != null)
next.handleRequest(condition);
}
}
}
测试类·
public class test {
public static void main(String[] args) {
HandlerImpl1 handlerImpl1 = new HandlerImpl1();
HandlerImpl2 handlerImpl2 = new HandlerImpl2();
HandlerImpl3 handlerImpl3 = new HandlerImpl3();
handlerImpl1.setNext(handlerImpl2);
handlerImpl2.setNext(handlerImpl3);
handlerImpl1.handleRequest("HandlerImpl2");
}
}