设计模式/结构型设计模式
简述
使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来
结合多个标准来获得单一标准
UML图
代码
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| @Slf4j @Getter public class OrangeCat extends Cat { private String color;
public OrangeCat(String color) { this.color = color; }
@Override public void run() { log.debug(“橘猫 run — >> “); } }
@Slf4j @Getter public class BlueCat extends Cat { private String color;
public BlueCat(String color) { this.color = color; }
@Override public void run() { log.debug(“蓝猫 run — >> “); } }
public interface CatFilter { List<Cat> filter(List<Cat> list); }
public class DefaultCatFilter implements CatFilter { @Override public List<Cat> filter(List<Cat> list) { List<Cat> orange = new ArrayList<>(); list.stream().map(cat -> { if (cat instanceof OrangeCat) { orange.add(cat); } return orange; }).collect(Collectors.toList()); return orange; } }
public class ColorFilter implements CatFilter { @Override public List<Cat> filter(List<Cat> list) { List<Cat> color = new ArrayList<>(); list.stream().map(cat -> { if (((OrangeCat) cat).getColor().equals("橘色")) { color.add(cat); } return color; }).collect(Collectors.toList()); return color; } }
public class Client { public static void main(String[] args) { OrangeCat orange1 = new OrangeCat(“橘色”); OrangeCat orange2 = new OrangeCat(“橘色”); OrangeCat orange3 = new OrangeCat(“橘白相间”); BlueCat blue1 = new BlueCat("蓝色"); BlueCat blue2 = new BlueCat("蓝黑色”); List < Cat > list = new ArrayList<>(); list.add(orange1); list.add(orange2); list.add(orange3); list.add(blue1); list.add(blue2); List<Cat> filter = new DefaultCatFilter().filter(list); List<Cat> color = new ColorFilter().filter(filter); color.forEach(Cat::run); } }
|