责任链模式
定义
责任链模式使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象连城一条链,并沿着这条链传递该请求,直到有对象处理它为止。
优点
降低耦合度。它将请求的发送者和接收者解耦
简化了对象,使得对象不需要知道链的结构
增强给对象指派职责的灵活性,允许动态地新增或者删除责任链
增加新的请求处理类方便
缺点
每个请求都是将责任链从头遍历到尾,如果较长,性能有影响
调试时不方便,调用逻辑复杂,可能会造成循环调用
public class ChainType {
public static int type_1 = 1;
public static int type_2 = 2;
public static int type_3 = 3;
public static int getChainType(Handler handler){
if(handler instanceof Handler1){
return type_1;
}
if(handler instanceof Handler2){
return type_2;
}
if(handler instanceof Handler3){
return type_3;
}
return -1;
}
}
public class Response {
private int chainType;
private String status;
public int getChainType() {
return chainType;
}
public void setChainType(int chainType) {
this.chainType = chainType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
public abstract class Handler {
private Handler nextHandler;
private int chainType;
protected void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public Response handleMessage(Response response){
if(getChainType()==response.getChainType()){
return this.excute(response);
}else{
return this.nextHandler.handleMessage(response);
}
}
protected abstract Response excute(Response response);
public int getChainType(){
return ChainType.getChainType(this);
}
}
public class Handler1 extends Handler{
@Override
protected Response excute(Response response) {
response.setStatus("Handler1 excuted");
return response;
}
}
public class Handler2 extends Handler{
@Override
protected Response excute(Response response) {
response.setStatus("Handler2 excuted");
return response;
}
}
public class Handler3 extends Handler{
@Override
protected Response excute(Response response) {
response.setStatus("Handler1 excuted");
return response;
}
}
public class Client {
public static void main(String[] args) {
Response response = new Response();
response.setChainType(ChainType.type_2);
Handler handle1 = new Handler1();
Handler handle2 = new Handler2();
Handler handle3 = new Handler3();
handle1.setNextHandler(handle2);
handle2.setNextHandler(handle3);
handle1.handleMessage(response);
System.out.println(response.getStatus());
}
}