责任链模式实战

Posted on 2018-11-02 15:26  三月老泉  阅读(959)  评论(0编辑  收藏  举报

 

责任链模式实战

第一步:设置参数dto

/**
* 请求DTO
*/
public class RequestDTO {

}

第二步:设置父类handler

public abstract class ParentHandler {
protected ParentHandler nextHandler;

protected ApplicationContext context = SpringContextUtil.getApplicationContext();

protected abstract boolean needHandler(RequestDTO request);

/**
* 子类handler需重写该handler()方法
* @param request
*/
protected void handler(RequestDTO request){
ParentHandler handler =this.nextHandler;
while (handler !=null){
if(handler.needHandler(request)){
handler.handler(request);
}
handler =handler.nextHandler;
}
}
/**
* 设置nextHandler
* @param nextHandler
* @return
*/
protected ParentHandler setNextHandler(ParentHandler nextHandler){
this.nextHandler =nextHandler;
return this.nextHandler;
}
}

第三步:设置子类handler

第一个子类handler

public class FirstHandler extends ParentHandler{
@Override
protected boolean needHandler(RequestDTO request) {
return true;
}

@Override
protected void handler(RequestDTO request){
System.out.println("FirstHandler.handler");
//此处只有在firstHandler中添加,其他的子类handler不能添加
super.handler(request);
}
}

第二个子类handler

public class SecondHandler extends ParentHandler {
@Override
protected boolean needHandler(RequestDTO request) {
return true;
}

@Override
protected void handler(RequestDTO request){
System.out.println("SecondHandler.handler");
}
}

第三个子类handler

public class ThirdHandler extends ParentHandler {
@Override
protected boolean needHandler(RequestDTO request) {
return true;
}

@Override
protected void handler(RequestDTO request){
System.out.println("ThirdHandler.handler");
}
}

子类handler按需添加 。。。。。

第四步:设置handler工厂类,main方法测试

public class HandlerFactroy {
private static ParentHandler handlerLinked =new FirstHandler();
static {
handlerLinked
.setNextHandler(new SecondHandler())
.setNextHandler(new ThirdHandler());
}

public static ParentHandler getHandlerLinked(){
return handlerLinked;
}

public static void main(String[] args){
RequestDTO requestDTO =new RequestDTO();
HandlerFactroy.getHandlerLinked().handler(requestDTO);
}

}