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.

Video

Example:

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.

Design

filter-design-pattern

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.

Criteria.java

Now lets implement a bunch of criteria to choose from.

Macintosh.java

4GBRam.java

I7Processor.java

ScreenSize15Inch.java

Likewise there can be a lot of other criteria e.g Windows.java, Ubuntu.java, 8GBRam.java, I3Processor.java etc.

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

AndCritera.java

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

LaptopScanner.java

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 *