简单模拟tomcat的filter过滤器模式

//Filter接口
public interface Filter {
    void work();

    default void doFilter(FilterChain filterChain) {
        work();
        filterChain.doFilter();
    }
}

//FilterChain接口
public interface FilterChain {
    void doFilter();
}

//FilterChain实现类
public class FilterChainImpl implements FilterChain {
    private List<Filter> filters = new ArrayList<>();
    private int pos = 0;

    public FilterChainImpl addFilter(Filter filter) {
        filters.add(filter);
        return this;
    }

    @Override
    public void doFilter() {
        if (pos < filters.size()) {
            Filter filter = filters.get(pos++);
            filter.doFilter(this);
        }
    }
}

//Filter实现类AFilter
public class AFilter implements Filter {
    @Override
    public void work() {
        System.out.println("A过滤器开始工作");
    }
}

//Filter实现类BFilter
public class BFilter implements Filter {
    @Override
    public void work() {
        System.out.println("B过滤器开始工作");
    }
}

//Filter实现类CFilter
public class CFilter implements Filter {
    @Override
    public void work() {
        System.out.println("C过滤器开始工作");
    }
}

//Test测试类
public class Test {
    public static void main(String[] args) {
        FilterChain filterChain = new FilterChainImpl()
        .addFilter(new AFilter())
        .addFilter(new BFilter())
        .addFilter(new CFilter());
        filterChain.doFilter();
    }
}

运行结果:
A过滤器开始工作
B过滤器开始工作
C过滤器开始工作

你可能感兴趣的:(设计模式,java)