Design Pattern:
Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations. 模式:过滤器模式使用criteria用来过滤一系列对象,criteria用来解耦
故事场景:根据2017年勇士队季后赛投篮表现,我要看下命中率超过40%的球员
球员
public class Person {
public Person(double rate, String name) {
this.rate = rate;
this.name = name;
}
//投篮命中率
private double rate;
//curry durant
private String name;
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
过滤器
public interface Criteria {
public List<Person> list(List<Person> peopleList);
}
public class ShootCriteria implements Criteria {
private final double DEFAULT_RATE = 0.4;
@Override
public List<Person> list(List<Person> peopleList) {
if (peopleList == null || peopleList.size() == 0) {
return new ArrayList<>();
}
List<Person> personList = new ArrayList<>();
for (Person person : peopleList) {
if (person.getRate() <= DEFAULT_RATE){
continue;
}
personList.add(person);
}
return personList;
}
}
##### 实验的开始
``` java
public class CriteriaDemo {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person(0.8,"durant"));
personList.add(new Person(0.9,"curry"));
Criteria criteria = new ShootCriteria();
List<Person> newList = criteria.list(personList);
if (newList.size() != 0){
for (Person person: newList){
System.out.println(person.getName()+",");
}
}
}
}
结果
