2

我认为最好用代码解释,这只是一个简单的例子:

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
}

哎呀,太丑了。基本上我有一个集合,我想通过某种筛子将它传递给仅继续处理满足特定条件的对象。我的猜测是有一个比一堆返回布尔值的方法更好的模式。

4

3 回答 3

2

您可以拥有IFilters.

像这样

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

    if (filterResult)
        break;
}
于 2010-03-11T17:06:52.750 回答
0

为什么不使用Bean-Query?它可以使您的代码可读。

List<MyPOJO> result=selectBean(MyPOJO.class).where(
                                                not(
                                                  anyOf(
                                                      value("aga",lessThan(21)),
                                                      value("age",greaterThan(50))
                                                  )
                                                )
                                            .executeFrom(myPojos).
于 2014-11-24T16:05:33.750 回答
0

您可能希望实现您的过滤器,以便它们获取一个集合,并返回一个过滤后的集合:

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

通过这种方式,您可以非常简单地将过滤器链接在一起。缺点是对于大型集合来说速度较慢并且占用更多空间;但代码更具可读性。

于 2010-03-11T17:20:04.253 回答