设计模式之策略模式(Strategy)-Java8
场景
定义一系列算法,封装每个算法,并使它们可互换。策略允许算法独立于使用它的客户端。
java8很好的支持了策略模式,在读《Java8 实战》的时候感受到了,这里就使用其中的例子
苹果有颜色和重量属性,现在比较苹果的属性,每种比较都是一种策略
策略模式
颜色枚举
public enum Color {
RED("red"), GREEN("green"), BROWN("brown"),BLUE("blue");
private String title;
Color(String title) {
this.title = title;
}
@Override
public String toString(){
return title;
}
}
苹果类
public class Apple {
private int weight;
private Color color;
public Apple(int weight, Color color) {
this.weight = weight;
this.color = color;
}
public int getWeight() {
return weight;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return "Apple{" +
"weight=" + weight +
", color=" + color +
'}';
}
}
比较策略接口
@FunctionalInterface
public interface Strategy {
boolean test(Apple apple);
}
颜色比较
public class ColorStrategy implements Strategy {
@Override
public boolean test(Apple apple) {
return apple.getColor().equals(Color.GREEN);
}
}
重量比计较
public class WeightStrategy implements Strategy {
@Override
public boolean test(Apple apple) {
return apple.getWeight() > 100;
}
}
比较器
public class Filter {
private Strategy stratgy;
public Filter(Strategy stratgy) {
this.stratgy = stratgy;
}
public void excute(List<Apple> apples){
for (Apple apple : apples) {
if (stratgy.test(apple)) {
System.out.println(apple);
}
}
}
}
测试
public class APP {
private List<Apple> apples;
@Before
public void before() {
apples = Arrays.asList(
new Apple(50, Color.BROWN),
new Apple(100, Color.BROWN),
new Apple(150, Color.RED),
new Apple(110, Color.GREEN),
new Apple(60, Color.GREEN)
);
}
/**
* 常规测试
*/
@Test
public void strategyTest() {
Filter colorFilter = new Filter(new ColorStrategy());
colorFilter.excute(apples);
System.out.println("==============");
Filter weightFilter = new Filter(new WeightStrategy());
weightFilter.excute(apples);
}
/**
* 匿名内部类测试
*/
@Test
public void strategyTestInnerClazzTest() {
Filter filter = new Filter(new Strategy() {
@Override
public boolean test(Apple apple) {
return apple.getColor().equals(Color.RED);
}
});
filter.excute(apples);
}
/**
* Java测试(lambd)
*/
@Test
public void strategyTestJava8Test() {
Filter filter = new Filter((apple -> {
return apple.getColor().equals(Color.GREEN);
}));
filter.excute(apples);
}
}
类图
使用java8进行改写
java封装了Predicate
使用Predict可以使代码非常简洁
Apple
和Color
不变
测试代码
public class App {
private List<Apple> apples;
@Before
public void before() {
apples = Arrays.asList(
new Apple(50, Color.BROWN),
new Apple(100, Color.BROWN),
new Apple(150, Color.RED),
new Apple(110, Color.GREEN),
new Apple(60, Color.GREEN)
);
}
/**
* 常规测试
*/
@Test
public void java8Test() {
excute(apples, apple -> {
return apple.getColor().equals(Color.GREEN);
});
}
public static void excute(List<Apple> apples, Predicate<Apple> predicate) {
for (Apple apple : apples) {
if (predicate.test(apple)) {
System.out.println(apple);
}
}
}
}
类图
java8使用了Predicate<T>
代替了Strategy