2.2 行为参数化

通过抽象“过滤苹果”,定义一个标准化接口,每种筛选定义具体的实现。

public interface ApplePredicate {
    boolean test(Apple apple);
}

public class AppleHeavyWeightPredicate implements ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return apple.getWeight() > 150;
    }
}

public class AppleGreenColorPredicate implements ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return "green".equals(apple.getColor());
    }
}
public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate applePredicate) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if (applePredicate.test(apple)) {
            result.add(apple);
        }
    }
    return result;
}

// invoke
filterApples(inventory, new AppleGreenColorPredicate());
filterApples(inventory, new AppleHeavyWeightPredicate());

扩展绿色的重苹果

// invoke
List<Apple> greenApples = filterApples(inventory, new AppleGreenColorPredicate());
List<Apple> greenWeightApples = filterApples(greenApples, new AppleHeavyWeightPredicate());

public class AppleGreenAndHeavyPredicate implements ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return "green".equals(apple.getColor()) && apple.getWeight() > 150;
    }
}

// invoke
filterApples(inventory, new AppleGreenAndHeavyPredicate());

测验2.1:编写灵活的prettyPrintApple方法

接受一个List,对于每个Apple,format生成String输出。

format方式要求行为参数化,方便扩展。

public interface AppleFormatter {
    public String format(Apple apple);

    public static void prettyPrintApple(List<Apple> inventory, AppleFormatter appleFormatter){
        for(Apple apple: inventory) {
            String output = appleFormatter.format(apple);
            System.out.println(output);
        }
    }
}

public class AppleStringFormatter implements AppleFormatter {
    @Override
    public String format(Apple apple) {
        return apple.toString();
    }
}

// invoke
prettyPrintApple(inventory, new AppleStringFormatter());
posted @ 2023-06-15 00:48  夜是故乡明  阅读(6)  评论(0编辑  收藏  举报