Design Pattern for filtering elements
I would like to know if exist any desing pattern for filtering elements base on some criteria (for example their UUIDS). I ended up in my code with things like this :
if(meetsSomeCriteria(thing))){
doSomething()
}
For instance, in my code I am filtering some elements based on their id by using a map :
if(!mymap.containsKey(myObject.getId())){
doSomet开发者_如何学Pythonhing();
mymap.put(myObject.getId(), myObject);
}
The problem is that this kind of code everywhere in the program. I would like to know if a design pattern can help me and give some hint/examples.
Thanks !!
You can use the CollectionUtils from apache commons -collections. Something like:
Collection matches = CollectionUtils.select(collection, new Predicate() {
public boolean evaluate(Object object) {
// evaluate predicate
}
});
Internally, it most likely just iterates over the collection and executes the predicate, but it saves your the boiler-plate code.
Intercepting-filter is one pattern used extensively with j2ee for filtering requests/responses. You can implement something similar to that.
精彩评论