顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
类图
Student类
class Student{
private String name;
private String sex;
public Student(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
过滤抽象类
/**
* 自定义抽象过滤器类
* @param <T1> 过滤对象类型
* @param <T2> 过滤属性类型
*/
abstract class AbstractFilter<T1,T2> {
List<T2> filterValues;
AbstractFilter<T1,T2> nextFilter;
AbstractFilter(List<T2> filterValues) {
this.filterValues = filterValues;
}
public void setNextFilter(AbstractFilter<T1,T2> filter) {
nextFilter = filter;
}
abstract void doFilter(List<T1> source);
}
名字过滤类
class NameFilter extends AbstractFilter<Student,String> {
NameFilter(List<String> filterValues) {
super(filterValues);
}
@Override
void doFilter(List<Student> list) {
list.removeIf(s -> filterValues.contains(s.getName()));
if (nextFilter != null) {
nextFilter.doFilter(list);
}
}
}
性别过滤类
class SexFilter extends AbstractFilter<Student,String> {
SexFilter(List<String> filterValues) {
super(filterValues);
}
@Override
void doFilter(List<Student> list) {
list.removeIf(s -> filterValues.contains(s.getSex()));
if (nextFilter != null) {
nextFilter.doFilter(list);
}
}
}
测试
public class Main {
public static void main(String[] args) {
Student xiaowang=new Student("xiaowang","man");
Student xiaoliu=new Student("xiaoliu","women");
Student xiaozhang=new Student("xiaozhang","man");
List<Student> studentList = new ArrayList<>();
studentList.add(xiaoliu);
studentList.add(xiaowang);
studentList.add(xiaozhang);
// 过滤xiaoliu
NameFilter nameFilter = new NameFilter(Arrays.asList("xiaoliu"));
// 过滤women
SexFilter sexFilter = new SexFilter(Arrays.asList("women"));
// 设置name的下一个过滤器
nameFilter.setNextFilter(sexFilter);
// 开始过滤
nameFilter.doFilter(studentList);
studentList.stream().forEach(stu-> System.out.println(stu.getName()+" "+stu.getSex()));
}
}
标签:filterValues,name,模式,sex,责任,Student,public,String
From: https://www.cnblogs.com/handsometaoa/p/17039911.html