过滤器模式

过滤器模式(Filter Pattern)或标准模式(Criteria Pattern)是一种设计模式,这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来

Class Diagram

Implementation

过滤器接口

1
2
3
public interface Filter {
<T> List<T> doFilter(List<T> list);
}

具体过滤器

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
public class ConcreteFilterA implements Filter {
@Override
public <T> List<T> doFilter(List<T> list) {
final List<T> result = new ArrayList<>();
list.forEach((item)->{
if(!item.equals("a")){
result.add(item);
}
});
return result;
}
}

public class ConcreteFilterB implements Filter {
@Override
public <T> List<T> doFilter(List<T> list) {
final List<T> result = new ArrayList<>();
list.forEach((item)->{
if(!item.equals("b")){
result.add(item);
}
});
return result;
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class FilterTest {

List<String> stringList = new ArrayList<>();
List<Filter> filterList = new ArrayList<>();

@Before
public void init(){
stringList.add("a");
stringList.add("b");
stringList.add("c");
stringList.add("d");

filterList.add(new ConcreteFilterA());
filterList.add(new ConcreteFilterB());
}

@Test
public void test() throws Exception{
filterList.forEach((filter -> {
List<String> result = filter.doFilter(stringList);
System.out.println("Filter"+filter.getClass().getSimpleName()+" : "+result.toString());
}));
}
}

Example

  • List.stream().filter()

Reflence