拥有一个自动装配的过滤器列表并不是解决问题的好方法。每个过滤器都依赖于需要传递给doFilter
方法的不同类型的参数。需要这样做使得该方法非常不灵活。是的,您可以使用可变参数,但它只会造成混乱。这就是为什么实现构建器来构建过滤器链以应用于产品集合的原因可能更容易。向构建器添加新过滤器成为一项微不足道的任务。当有很多不同的参数在起作用时,建造者模式非常有用。
考虑有这个接口:
public interface CollectionFilter<T> {
public Collection<T> doFilter(Collection<T> collection);
}
将所有过滤器应用于集合的过滤器链接类:
public class CollectionFilterChain<T> {
private final List<CollectionFilter<T>> filters;
public CollectionFilterChain(List<CollectionFilter<T>> filters) {
this.filters = filters;
}
public Collection<T> doFilter(Collection<T> collection) {
for (CollectionFilter<T> filter : filters) {
collection = filter.doFilter(collection);
}
return collection;
}
}
两种CollectionFilter<T>
实现:
public class InStockFilter<T> implements CollectionFilter<T> {
public Collection<T> doFilter(Collection<T> collection) {
// filter
}
}
public class MinPriceFilter<T> implements CollectionFilter<T> {
private final float minPrice;
public MinPriceFilter(float minPrice) {
this.minPrice = minPrice;
}
public Collection<T> doFilter(Collection<T> collection) {
// filter
}
}
还有一个构建器,可让您以简单的方式构建过滤器链:
public class CollectionFilterChainBuilder<T> {
List<CollectionFilter<T>> filters;
public CollectionFilterChainBuilder() {
filters = new ArrayList<CollectionFilter<T>>();
}
public CollectionFilterChainBuilder<T> inStock() {
filters.add(new InStockFilter<T>());
return this;
}
public CollectionFilterChainBuilder<T> minPrice(float price) {
filters.add(new MinPriceFilter<T>(price));
return this;
}
public CollectionFilterChain<T> build() {
return new CollectionFilterChain<T>(filters);
}
}
使用构建器可以轻松创建过滤器链,如下所示:
CollectionFilterChainBuilder<Product> builder =
new CollectionFilterChainBuilder();
CollectionFilterChain<Product> filterChain =
builder.inStock().minPrice(2.0f).build();
Collection<Product> filteredProducts =
filterChain.doFilter(products);
在更动态的设置中,您可以使用如下构建器:
CollectionFilterChainBuilder<Product> builder = new CollectionFilterChainBuilder();
if (filterInStock) {
builder.inStock();
}
if (filterMinPrice) {
builder.minPrice(minPrice);
}
// build some more