策略模式之前
/**
* 策略模式之前
* <p>
* 例子:
* 穿白色的衣服返回口红100号
* 穿红色的衣服返回口红300号
* .....
*/
public class NoStrategy {
public static int getLipstick(String clothes) {
if ("white".equals(clothes)) {
return 1;
} else if ("red".equals(clothes)) {
return 2;
} else if ("yellow".equals(clothes)) {
return 3;
}
return 0;
}
}
策略模式
/**
* 策略接口
*/
public interface ClothesLipstick {
int getLipstick();
}
/**
* 白色衣服策略接口实现
*/
public class WhiteClothesLipstick implements ClothesLipstick {
@Override
public int getLipstick() {
return 1;
}
}
/**
* 红色策略接口模式
*/
public class RedClothesLipstick implements ClothesLipstick {
@Override
public int getLipstick() {
return 2;
}
}
/**
* 黄色衣服策略接口实现
*/
public class YellowClothesLipstick implements ClothesLipstick {
@Override
public int getLipstick() {
return 3;
}
}
使用方式
public class StrategyDemo {
public static void main(String[] args) {
noStrategy();
System.out.println("====");
strategy();
}
/**
* 不用策略模式
*/
private static void noStrategy() {
List<String> clothes = Lists.newArrayList();
clothes.add("red");
clothes.add("white");
clothes.add("yellow");
clothes.stream().forEach(item -> System.out.println(item + ":" + NoStrategy.getLipstick(item)));
}
/**
* 使用策略模式
*/
private static void strategy() {
Map<String, ClothesLipstick> map = Maps.newHashMap();
map.put("red", new RedClothesLipstick());
map.put("white", new WhiteClothesLipstick());
map.put("yellow", new YellowClothesLipstick());
map.forEach((k, v) -> System.out.println(k + ":" + v.getLipstick()));
}
}
总结:对修改关闭,对扩展开放。代码的扩展性更好