过滤器链模式

public interface IConfigFilterChain {

    public void doFilter(IConfigRequest request, IConfigResponse response);
    
}

public interface IConfigRequest {

    public Object getParameter(String key);

    public IConfigContext getConfigContext();

}

public interface IConfigResponse {
    
    public Object getParameter(String key);

    public IConfigContext getConfigContext();

}

public interface IConfigContext {
    
    public Object getParameter(String key);

    public void setParameter(String key, Object value);
}

public class ConfigFilterChainManager implements IConfigFilterChain {

    private List filters = Lists.newArrayList();

    public synchronized ConfigFilterChainManager addFilter(IConfigFilter filter) {
        // ¸ù¾Ýorder´óС˳Ðò²åÈë
        int i = 0;
        while (i < this.filters.size()) {
            IConfigFilter currentValue = this.filters.get(i);
            if (currentValue.getFilterName().equals(filter.getFilterName())) {
                break;
            }
            if (filter.getOrder() >= currentValue.getOrder() && i < this.filters.size()) {
                i++;
            } else {
                this.filters.add(i, filter);
                break;
            }
        }

        if (i == this.filters.size()) {
            this.filters.add(i, filter);
        }
        return this;
    }
    

    @Override
    public void doFilter(IConfigRequest request, IConfigResponse response) throws DiamondException {
        new VirtualFilterChain(this.filters).doFilter(request, response);
    }

    private static class VirtualFilterChain implements IConfigFilterChain {

        private final List additionalFilters;

        private int currentPosition = 0;

        public VirtualFilterChain(List additionalFilters) {
            this.additionalFilters = additionalFilters;
        }

        @Override
        public void doFilter(final IConfigRequest request, final IConfigResponse response) throws DiamondException {
            if (this.currentPosition == this.additionalFilters.size()) {
                return;
            } else {
                this.currentPosition++;
                IConfigFilter nextFilter = this.additionalFilters.get(this.currentPosition - 1);
                nextFilter.doFilter(request, response, this);
            }
        }
    }

}

你可能感兴趣的:(过滤器链模式)