java过滤器模式
前言
过滤器模式(Filter Pattern),这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。这种类型的设计模式属于结构型模式,它结合多个标准来获得单一标准。
过滤器模式是很多java框架常用的模式之一
1,故事
人事通过招聘,面试,从而过滤出不同水平的开发工程师,进而选择通过。
2,定义开发工程师对象
@Data
public class DevelopEngineer {
//技能等级
private String level;
//姓名
private String name;
//年龄
private Integer age;
DevelopEngineer(String level,String name,Integer age){
this.level = level;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "开发工程师:" +
"{ 职业等级 : '" + level + '\'' +
", 姓名:'" + name + '\'' +
", 年龄: " + age +
'}';
}
}
3,定义过滤器顶层接口 filter
public abstract class Filter {
//筛选
public abstract List<DevelopEngineer> choose(List<DevelopEngineer> devList);
}
4,HighDevFilter 高级开发过滤器
public class HighDevFilter extends Filter{
//选择高级工程师
@Override
public List<DevelopEngineer> choose(List<DevelopEngineer> devList) {
List<DevelopEngineer> res = new ArrayList<>();
for (DevelopEngineer engineer : devList) {
if(engineer.getLevel().equals("高级")){
res.add(engineer);
}
}
return res;
}
}
5,MiddleDevFilter 中级开发过滤器
public class MiddleDevFilter extends Filter{
//选择中级工程师
@Override
public List<DevelopEngineer> choose(List<DevelopEngineer> devList) {
List<DevelopEngineer> res = new ArrayList<>();
for (DevelopEngineer engineer : devList) {
if(engineer.getLevel().equals("中级")){
res.add(engineer);
}
}
return res;
}
}
6,年龄过滤器
public class AgeDevFilter extends Filter{
@Override
public List<DevelopEngineer> choose(List<DevelopEngineer> devList) {
List<DevelopEngineer> res = new ArrayList<>();
for (DevelopEngineer engineer : devList) {
//选择出年龄小于35 大于 25 的工程师
if(engineer.getAge() > 25 && engineer.getAge() <= 35){
res.add(engineer);
}
}
return res;
}
}
7,测试
过滤出年龄大约25小于35的高级开发工程师
public static void main(String[] args) {
List<DevelopEngineer> list = new ArrayList<>();
list.add(new DevelopEngineer("高级","东升",28));
list.add(new DevelopEngineer("高级","静子",37));
list.add(new DevelopEngineer("中级","红岩",25));
list.add(new DevelopEngineer("初级","晓东",30));
list.add(new DevelopEngineer("中级","珂子",20));
list.add(new DevelopEngineer("中级","春子",20));
list.add(new DevelopEngineer("高级","刘一",30));
//初始化
HighDevFilter highDevFilter = new HighDevFilter();
AgeDevFilter ageDevFilter = new AgeDevFilter();
//两次过滤输出
print(ageDevFilter.choose(highDevFilter.choose(list)));
}
private static void print(List<DevelopEngineer> list){
for (DevelopEngineer engineer : list) {
System.out.println(engineer.toString());
}
}
8,结果
开发工程师:{ 职业等级 : '高级', 姓名:'东升', 年龄: 28}
开发工程师:{ 职业等级 : '高级', 姓名:'刘一', 年龄: 30}
总结
过滤器是较为常用的设计模式之一,可以配合责任链模式,进行链式过滤