责任链模式(两种写法)

1、经典写法方式

如果需要可以加个排序

 /**
 * @author: QXY
 * @classDescribe:
 * @createTime: 2019/3/15
 * @version: 1.0
 */
public abstract class AbstractFilter implements Ordered{

    protected AbstractFilter filter;

    public abstract void doFilter(String request,String resp);

    public void setNext(AbstractFilter filter) {
        this.filter=filter;
    }

    public void next(String request,String resp){
        if (null!=this.filter){
            filter.doFilter(request, resp);
        }
    }
}
/**
 * @author: QXY
 * @classDescribe:
 * @createTime: 2019/3/15
 * @version: 1.0
 */
public class FirstFilter extends AbstractFilter {

    @Override
    public void doFilter(String request,String resp) {
        System.out.println("=====first filter" + request);
        next(request,resp);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
 /**
 * @author: QXY
 * @classDescribe:
 * @createTime: 2019/3/15
 * @version: 1.0
 */
public class TestMain {
    public static AbstractFilter init(){
        List filterList=new ArrayList<>();

        filterList.add(new SecondFilter());
        filterList.add(new ThirdFilter());
        filterList.add(new FirstFilter());
        /*
         * 这里可以加排序
         */
        filterList.sort((e,h)->e.getOrder()>h.getOrder()?1:-1);

        for(int i=0;i

2、另一种经典

public interface IFilterShaoxi {
    void doFilter(Object request,Object response,IFilterShaoxi fc);
}
/**
 * @author: QXY
 * @classDescribe:
 * @createTime: 2019/3/14
 * @version: 1.0
 */
public class FilterChainShaoXi implements IFilterShaoxi {

    List filterShaoxis=new ArrayList<>();
    int index=0;
    public FilterChainShaoXi addFilter(IFilterShaoxi filterShaoxi){
        filterShaoxis.add(filterShaoxi);
        return this;
    }
    @Override
    public void doFilter(Object request,Object response,IFilterShaoxi fc) {
        if(index == filterShaoxis.size()){
            return ;
        }
        IFilterShaoxi filter = filterShaoxis.get(index);
        index++;
        filter.doFilter(request, response, fc);
    }
    public static void main(String[] args) {
        FilterChainShaoXi filterChainShaoXi=new FilterChainShaoXi();
        filterChainShaoXi.addFilter(new FirstFilter());
        filterChainShaoXi.addFilter(new SecondFilter());
        filterChainShaoXi.addFilter(new ThirdFilter());
        filterChainShaoXi.addFilter(new WriteFilter());
        filterChainShaoXi.doFilter("yandaye-","",filterChainShaoXi);
    }
}
/**
 * @author: QXY
 * @classDescribe:
 * @createTime: 2019/3/14
 * @version: 1.0
 */
public class FirstFilter implements IFilterShaoxi {

    @Override
    public void doFilter(Object request,Object response,IFilterShaoxi fc) {

        System.out.println("=====first fitler before====");
        String tmp =String.valueOf(request);
        tmp = tmp+"firstFilter";

        fc.doFilter(tmp,response,fc);

    }
}

注:参考大话设计模式

你可能感兴趣的:(责任链模式(两种写法))