Filter Design Pattern

      No Comments on Filter Design Pattern

What Is Filter Design Pattern?

Filter design pattern is used for building a criteria to filter items or objects dynamically. You can choose your own criteria and apply it on your objects to filter out the desired objects.

When to use Filter Design Pattern?

Its easy to figure out when one should use filter design pattern. When you have a requirement where you want to add filters dynamically or you are implementing multiple functionalities and most of them require different filter criteria to filter something. In that case instead of hard coding the filters inside the functionalities, you can create filter criteria and re-use it wherever required.



Lets understand Filter Design Pattern with an example. All the code used below is available on github.

Lets build a hypothetical scenario to understand this pattern better.

You are building a tool to help tech-ops team in your company to distribute laptops to employees according to their configuration requirements. Each role in company has a different configuration requirement. Now tech-ops team have a very hard time to filter out the laptops as per the employee requirement because its a manual process.

The tool you are building provides a functionality to the employees to add filters to search for their desired laptop. The filters may change across the employees.

This is a very good place to use the filter design pattern, as you know that filters may change across employees. Now lets implement the solution.



Lets define the interface which every criteria has to implement. This interface has a method which meets the employee requirement and returns the filtered laptops.

Now lets implement a bunch of criteria to choose from.

Likewise there can be a lot of other criteria e.g,,, etc.

There is two more criteria which are very important AndCriteria and OrCriteria. Both are used to combine multiple criteria.

Now that we have all criteria implemented, lets use them to filter out the desired laptops.

This class combines multiple criteria and prints the laptops which matches with employees configuration.

Thats all folks, I hope now you have a better understanding of filter design pattern. If you have any comments, suggestions or feedback, please leave a comment below. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *