美文网首页
策略模式

策略模式

作者: 杨殿生 | 来源:发表于2018-09-20 15:42 被阅读0次

筛选苹果

    //筛选绿色苹果
    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;
    }

第一个版本

把颜色作为参数

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

如果在加上重量呢

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

这样其实是复制了大量的代码,那么如果不复制代码怎么写呢,那就需要加入一个flag用来区分是按颜色筛选还是用重量筛选


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

这么写出来代码很糟糕,并且如果说我要按大小,形状,产品筛选怎么办?在加入组合筛选又该怎么办?

使用策略模式

策略模式类图.png

定义策略接口

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

分别实现策略

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

改造筛选方法,将策略传入

    public static List<Apple> filterApples(List<Apple> inventory,ApplePredicate predicate){
        List<Apple> result = new ArrayList<>();
        for (Apple apple:inventory){
            if (predicate.test(apple)){
                result.add(apple);
            }
        }
        return result;
    }

这样在调用对应策略就可以了

        filterApples(lists,new AppleHeavyWeightPredicate());
        filterApples(lists,new AppleGreenColorPredicate());

java8 中有更好的实现方式使用流操作即可

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/yslnnftx.html