Friday, 17 May 2013

Filter Pattern Example - JAVA


Filter pattern is mainly used to filter group of objects based on some criteria  We can see one simple example of this filter pattern. Here we are going to filter laptops based on company and OS. Use following steps to build example.
1. Create class Laptops as given below.
public class Laptops {
String company, os;
int bits;
public Laptops(String company, String os, int bits) {
this.company = company;
this.os = os;
this.bits = bits;
}//Laptops
public String getCompany() { return company; }
public String getOs() { return os; }
public int getBits() { return bits; }
}//class Laptops

2. Create interface Filter as given below.
import java.util.List;
public interface Filter {
List<Laptops> filterObjects(List<Laptops> laptops);
}

3. Create class HclFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class HclFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> hclLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getCompany().equalsIgnoreCase("hcl"))
hclLaptops.add(laptops.get(i));
return hclLaptops;
}//filterObjects
}//HclFilter

4. Create class WindowsOsFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class WindowsOsFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> windowsOsLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getOs().equalsIgnoreCase("windows"))
windowsOsLaptops.add(laptops.get(i));
return windowsOsLaptops;
}//filterObjects
}//WindowsOsFilter

5. And now our demo class for filter pattern.
import java.util.ArrayList;
import java.util.List;
public class FilterDemo {
public static void main(String args[]) {
List<Laptops> allLaptops = new ArrayList<Laptops>();
allLaptops.add(new Laptops("hcl", "windows", 32)); allLaptops.add(new Laptops("hcl", "linux", 32));
allLaptops.add(new Laptops("hcl", "solaries", 64)); allLaptops.add(new Laptops("dell", "windows", 32));
allLaptops.add(new Laptops("dell", "linux", 32)); allLaptops.add(new Laptops("dell", "solaries", 64));
Filter hclLaptops = new HclFilter();
Filter windowsOsLaptops = new WindowsOsFilter();
List<Laptops> filteredLaptops = hclLaptops.filterObjects(allLaptops);
System.out.print("\nAll HCL laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
filteredLaptops = null;
filteredLaptops = windowsOsLaptops.filterObjects(allLaptops);
System.out.print("\nAll windows os laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
}//PSVM
}//class FilterDemo

You can add more filters and can add "AND" & "OR" filters as well.

No comments:

Post a Comment