Design pattern for filtering objects

I have a list of objects to be filtered.

This filtering will consist of at least 3 rules.

So for example:

public class Filtering { List<MyObject> myObjectList; List<MyObject> filterStep1(List<MyObject> myObjectList){ for(Myobject myobj : myObjectList){ if(isCriteriaSatisified){ continue } else { removeThisObjectFromList } } } List<MyObject> filterStep2(List<MyObject> myObjectList){ for(Myobject myobj : myObjectList){ if(isCriteriaSatisified){ continue } else { removeThisObjectFromList } } } } 

I like this approach because it is simple, self-sufficient and can very easily see what it is trying to achieve.

But maybe there is a design template that I should use instead?

The Chain of Responsibility template is what I am considering when filterStep1 and filterStep2 in the above code are reorganized into a separate hander.

+5
source share
2 answers

This is a pipe and filter pattern, and although your implementation is fine, it’s best not to hard code the filtering logic in the methods. Instead, write a Predicate<MyObject> for each of your logical conditions (either built-in in Java 8 or from Guava). This is much easier to verify and can be easily applied to existing clean APIs such as Streams API or Guava views.

+4
source

One option using Java 8 threads:

 myObjects.stream().filter( this::isCriteriaSatisified ).filter( this::anotherCriteria ) 

Assuming you have a boolean isCriteriaSatisified(myObj) method in your class. Then you can collect this thread into another list.

+2
source

Source: https://habr.com/ru/post/1203716/


All Articles