在数据集合上运行流程的良好设计模式?
我认为最好用代码来解释,这只是一个简单的例子:
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
}
哎呀,这太丑了。基本上我有一个集合,我想将它通过某种筛子,以仅继续处理满足特定条件的对象。我的猜测是,有一个比一堆返回布尔值的方法更好的模式。
Best explained with code I think, this is just a simple example:
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
}
Yikes that's ugly. Basically I have a collection and I'd like to pass it through a sieve of sorts to only continue processing the objects that meet a certain criteria. My guess is there is a better pattern for this than a bunch of methods that return booleans.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以拥有
IFilters
列表。像这样
You can have list of
IFilters
.like so
您可能希望实现过滤器,以便它们接受一个集合,并返回一个过滤后的集合:
这样您就可以非常简单地将过滤器链接在一起。缺点是对于大型集合,速度较慢且占用更多空间;但代码的可读性要高得多。
You may want to implement your filters such that they take a collection, and return a filtered collection:
This way you can chain together filters very trivially. The downside is that for large collections it is slower and takes more space; but the code is a lot more readable.
为什么不使用Bean-Query?它可以使你的代码可读。
Why not use Bean-Query? it can make your code readable.