目的:
定义一个家族算法,并封装好其中每一个,使它们可以互相替换。策略模式使算法的变化独立于使用它的客户。策略模式允许在运行时选择最匹配的算法。
程序示例:
屠龙是一项危险的职业。有经验将会使它变得简单。经验丰富的屠龙者对不同类型的龙有不同的战斗策略。
1.定义策略及实现
public interface DragonSlayingStrategy{
void execute();
}
@Slf4j
public class MeleeStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("With your Excalibur you sever the dragon's head!");
}
}
@Slf4j
public class ProjectileStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
}
}
@Slf4j
public class SpellStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
}
}
2.定义策略使用类
public class DragonSlayer {
private DragonSlayingStrategy strategy;
public DragonSlayer(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void changeStrategy(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void goToBattle() {
strategy.execute();
}
}
lambda策略实现
public class LambdaStrategy{
public enum Strategy implements DragonSlayingStrategy{
MeleeStrategy(()->System.out.println("With your Excalibur you severe the dragon's head!")),
ProjectileStrategy(()->System.out.println("You shoot the dragon with the magical crossbow and it falls dead on the ground!")),
SpellStrategy(()->System.out.println("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
private final DragonSlayingStrategy strategy;
Strategy(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
@Override
public void execute() {
strategy.execute();
}
}
}
3.测试输出
System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
System.out.println("Red dragon emerges.");
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
/*
Green dragon spotted ahead!
With your Excalibur you sever the dragon's head!
Red dragon emerges.
You shoot the dragon with the magical crossbow and it falls dead on the ground!
Black dragon lands before you.
You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
*/
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy);
dragonSlayer.goToBattle();
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy);
dragonSlayer.goToBattle();
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy);
dragonSlayer.goToBattle();
类图:

3326

被折叠的 条评论
为什么被折叠?



