2.1 应对不断变化的需求

2.1.1 初试牛刀:筛选绿苹果

筛选绿苹果的经典写法:

public static List<Apple> filterGreenApples(List<Apple> inventory) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if ("green".equals(apple.getColor())) {
            result.add(apple);
        }
    }
    return result;
}

// invoke
filterGreenApples(inventory);

筛选红苹果

public static List<Apple> filterRedApples(List<Apple> inventory) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if ("red".equals(apple.getColor())) {
            result.add(apple);
        }
    }
    return result;
}

// invoke
filterRedApples(inventory);

2.1.2 再展身手:把颜色作为参数

筛选更多颜色时,例如浅绿色,暗红色,黄色等,代码模式重复,数量快速增长。

抽象颜色作为参数,适应颜色变化。

public static List<Apple> filterApplesByColor(List<Apple> inventory, String color) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if (apple.getColor().equals(color)) {
            result.add(apple);
        }
    }
    return result;
}

// invoke
filterApplesByColor(inventory, "green");
filterApplesByColor(inventory, "red");

进一步需要区分轻苹果和重苹果,重的苹果一般是重量大于150克。
同理把重量作为参数。

public static List<Apple> filterApplesByWeight(List<Apple> inventory, int weight) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if (apple.getWeight() > weight) {
            result.add(apple);
        }
    }
    return result;
}

// invoke
filterApplesByWeight(inventory, 150);

2.1.3 第三次尝试:对你能想到的每个属性做筛选

每个属性作为入参,通过额外变量控制筛选属性。

public static List<Apple> filterApples(List<Apple> inventory, String color, Integer weight, int flag) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if ((flag == 0 && apple.getColor().equals(color))
                || (flag == 1 && apple.getWeight() > weight)) {
            result.add(apple);
        }
    }
    return result;
}

// invoke
filterApples(inventory, "green", null, 0);
filterApples(inventory, null, 150, 1);

看似整合筛选相关代码,实则耦合严重

  1. 调用时,传递不相关的筛选属性,同时需明确指定筛选属性;
  2. 随着筛选属性增加,方法入参数量增加,重构需保留原有方法,造成冗余;
posted @ 2023-06-15 00:46  夜是故乡明  阅读(7)  评论(0编辑  收藏  举报