赞
踩
过滤器模式(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; } }
过滤器接口
import java.util.List;
public interface Filter {
List<Person> filter(List<Person> people);
}
实现过滤器
用来过滤成人
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; } }
运行类
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()); } } }
运行结果:
name:b
age:20
name:c
age:21
name:d
age:56
发现输出的都是年龄超过18岁的,实现了过滤的功能
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。