当前位置:   article > 正文

JAVA 二十三种设计模式大全(十八)过滤器模式(Filter Pattern)_过滤器模式不在23

过滤器模式不在23

文章目录

概念

过滤器模式(Filter Pattern)或标准模式(Criteria Pattern)是一种设计模式,这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。这种类型的设计模式属于结构型模式,它结合多个标准来获得单一标准。

设计

代码设计如下图

请添加图片描述

需要说明下的就是性别用了一个枚举类,以方便在过滤时,可以把过滤的性别作为参数传入过滤器。

考虑到过滤器的接口方法入参只有一个(为了抽象程度高,所以不扩展更多入参)

所以把额外的属性(比如过滤的年龄,性别)作为构造方法的入参传入,而不作为过滤方法入参。

涉及到的过滤方式有:

按年龄过滤、按性别过滤、年龄和性别的交集、年龄和性别的并集

代码

public interface PeopleFilter {
   
    List<People> doPeopleFilter(List<People> peopleList);
}
  • 1
  • 2
  • 3
  • 4
public enum SexEnum {
   
    MALE(1, "男"),
    FAMALE(2, "女");

    int code;
    String msg;
    SexEnum(int code, String msg){
   
        this.code = code;
        this.msg = msg;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
@Data
public class People {
   
    private int age;
    private String name;
    private SexEnum sexEnum;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
public class SexFilter implements PeopleFilter {
   
    private SexEnum sexEnum;
    public SexFilter(SexEnum sexEnum){
   
        // 在构造方法时指定性别
        this.sexEnum = sexEnum;
    }
    @Override
    public List<People> doPeopleFilter(List<People> peopleList) {
   
        List<People> result = new ArrayList<>();
        for (People people : peopleList) {
   
            if (this.sexEnum.equals(people.getSexEnum())) {
   
                result.add(people);
            }
      
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号