当前位置:   article > 正文

设计模式-过滤模式_过滤器 模式 代码

过滤器 模式 代码

定义

过滤器模式(Filter)也叫条件模式(Criteria),这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。当我们想要选择满足一个或多个条件的对象子集时,此设计模式非常有用。它属于结构模式。

结构图

在这里插入图片描述

用途

用于过滤数据,得到自己想要的数据

代码实现

需要过滤的实体类

public class Person{
    private int age;
    private String name;

    public Person(int age, String name){
        this.age = age; //年龄
        this.name = name; //姓名
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub

        return "name:" + name + "\n" + "age:" + age;

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

过滤器接口

import java.util.List;

public interface Filter {
    List<Person> filter(List<Person> people);
}
  • 1
  • 2
  • 3
  • 4
  • 5

实现过滤器
用来过滤成人

import java.util.ArrayList;
import java.util.List;

public class AldultFilter implements Filter{

    @Override
    public List<Person> filter(List<Person> people) {
        // TODO Auto-generated method stub
        List<Person> aldult = new ArrayList<>();
        for (Person p : people) {
            if (p.getAge() > 18) {
                aldult.add(p);
            }
        }
        return aldult;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

运行类

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Person a = new Person(2, "a");
        Person b = new Person(20, "b");
        Person c = new Person(21, "c");
        Person d = new Person(56, "d");
        List<Person> people = new ArrayList<>();
        people.add(a);
        people.add(b);
        people.add(c);
        people.add(d);
        Filter aldultFilter = new AldultFilter();
        List<Person> aldult = aldultFilter.filter(people);
        for(Person p:aldult){
            System.out.println(p.toString());
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

运行结果:

name:b
age:20
name:c
age:21
name:d
age:56
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

发现输出的都是年龄超过18岁的,实现了过滤的功能

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/481980
推荐阅读
相关标签
  

闽ICP备14008679号