1 基本概念:
这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把他们连接在一起。
2 person对象,Criteria接口和实现该接口的实体类,来过滤Persond对象的列表。
样例:
//对person类进行过滤
public class Person{
private String name;
private String gender;
private String maritalStatus;
public Person(String name,String gender,String maritalStatus){
this.name = name;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
}
//为标准Criteria创建一个接口
public interface Criteria{
public List meetCriteria(List persons);
}
//CriteriaMale 实现接口
public class CriteriaMale implements Criteria{
public List meetCriteria(List persons){
List malePersons = new ArrayList();
for(Person person:persons){
if(person.getGender().equalsIgnoreCase(“MALE”)){
malePersons.add(person);
}
}
return malePersons;
}
}
//CriteriaFemale 实现接口
public class CriteriaFemale implements Criteria {
@Override
public List meetCriteria(List persons) {
List femalePersons = new ArrayList();
for (Person person : persons) {
if(person.getGender().equalsIgnoreCase(“FEMALE”)){
femalePersons.add(person);
}
}
return femalePersons;
}
}
//CriteriaSingle实现接口
public class CriteriaSingle implements Criteria {
@Override
public List meetCriteria(List persons) {
List singlePersons = new ArrayList();
for (Person person : persons) {
if(person.getMaritalStatus().equalsIgnoreCase(“SINGLE”)){
singlePersons.add(person);
}
}
return singlePersons;
}
}
//CriteriaPatternDemo
public class CriteriaPatternDemo {
public static void main(String[] args) {
List persons = new ArrayList();
persons.add(new Person(“Robert”,“Male”, “Single”));
persons.add(new Person(“John”,“Male”, “Married”));
persons.add(new Person(“Laura”,“Female”, “Married”));
persons.add(new Person(“Diana”,“Female”, “Single”));
persons.add(new Person(“Mike”,“Male”, “Single”));
persons.add(new Person(“Bobby”,“Male”, “Single”));
Criteria male = new CriteriaMale();
Criteria female = new CriteriaFemale();
Criteria single = new CriteriaSingle();
System.out.println("Males: ");
printPersons(male.meetCriteria(persons));
System.out.println("\nFemales: ");
printPersons(female.meetCriteria(persons));
System.out.println("\nSingle Males: ");
printPersons(singleMale.meetCriteria(persons));
}
}
/输出/
Males:
Person : [ Name : Robert, Gender : Male, Marital Status : Single ]
Person : [ Name : John, Gender : Male, Marital Status : Married ]
Person : [ Name : Mike, Gender : Male, Marital Status : Single ]
Person : [ Name : Bobby, Gender : Male, Marital Status : Single ]
Females:
Person : [ Name : Laura, Gender : Female, Marital Status : Married ]
Person : [ Name : Diana, Gender : Female, Marital Status : Single ]
Single Males:
Person : [ Name : Robert, Gender : Male, Marital Status : Single ]
Person : [ Name : Mike, Gender : Male, Marital Status : Single ]
Person : [ Name : Bobby, Gender : Male, Marital Status : Single ]