与代码我认为最佳解释的,这仅仅是一个简单的例子:

public class MyPOJO {

    public String name;
    public int age;

    public MyPOJO(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class MyProcessor {

    public List<MyPOJO> process(List<MyPOJO> mypojos) {
        List<MyPOJO> temp = new ArrayList<MyPOJO>; 
        for (int i=0; i <moypojos.size(); i++) {
            if (filterOne(mypojos[i])) continue;
            if (filterTwo(mypojos[i])) continue;
            if (filterThree(mypojos[i])) continue;
            temp.add(mypojos[i];
        }
    }

    public boolean filterOne(MyPOJO mypojo) {
        // in practice filters aren't so basic
        return (mypojo.age < 21);
    }
    // assume implementations for the other filter methods
}

让人惊讶这是难看。基本上我有一个集合,我想通过它通过各种各样的筛子,只继续处理符合一定条件的对象。我的猜测是有这个比一堆返回布尔方法更好的模式。

有帮助吗?

解决方案

您可以IFilters的名单。

像这样

boolean filtersResult = false;
for (IFilter filter : filters) {
    filterResult = filter.process(mypojos[i])

    if (filterResult)
        break;
}

其他提示

您可能要实现你的过滤器,他们采取的集合,并返回一个过滤系列:

public interface IFilter<E> {
  public Collection<E> filter(Collection<E> input);
}

这样,您就可以连续使用过滤器很平凡。不足之处是非常大的集合是慢,需要更多的空间;但是代码是很多更具有可读性。

为什么不使用豆查询?它可以使你的代码的可读性。

List<MyPOJO> result=selectBean(MyPOJO.class).where(
                                                not(
                                                  anyOf(
                                                      value("aga",lessThan(21)),
                                                      value("age",greaterThan(50))
                                                  )
                                                )
                                            .executeFrom(myPojos).
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top