当实现某一个功能存在多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能,如数据排序策略有冒泡排序、选择排序、插入排序、二叉树排序等。
如果使用多重条件转移语句实现(即硬编码),不但使条件语句变得很复杂,而且增加、删除或更换算法要修改原代码,不易维护,违背开闭原则。如果采用策略模式就能很好解决该问题。
什么是策略(Strategy)模式?
策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。
策略模式的主要优点如下。
多重条件语句不易维护,而使用策略模式可以避免使用多重条件语句。
策略模式提供了一系列的可供重用的算法族,恰当使用继承可以把算法族的公共代码转移到父类里面,从而避免重复的代码。
策略模式可以提供相同行为的不同实现,客户可以根据不同时间或空间要求选择不同的。
策略模式提供了对开闭原则的完美支持,可以在不修改原代码的情况下,灵活增加新算法。
策略模式把算法的使用放到环境类中,而算法的实现移到具体策略类中,实现了二者的分离。
其主要缺点如下。
客户端必须理解所有策略算法的区别,以便适时选择恰当的算法类。
策略模式造成很多的策略类。
例子
在这个例子中({@link DragonSlayingStrategy})封装了一个算法。包含对象({@link DragonSlayer})可以通过改变策略来改变其行为。
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// GoF Strategy pattern
LOGGER.info("Green dragon spotted ahead!(绿色的龙在前面)");
var dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
LOGGER.info("Red dragon emerges.(红龙出现了)");
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
LOGGER.info("Black dragon lands before you.(黑龙在你面前降落)");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
// Java 8 Strategy pattern
LOGGER.info("Green dragon spotted ahead!(前方有青龙!)");
dragonSlayer = new DragonSlayer(
() -> LOGGER.info("java8 With your Excalibur you severe the dragon's head!(你用神剑斩断了龙首!)"));
dragonSlayer.goToBattle();
LOGGER.info("Red dragon emerges.(红龙出现了)");
dragonSlayer.changeStrategy(() -> LOGGER.info(
"java8 You shoot the dragon with the magical crossbow and it falls dead on the ground!(你用魔法弩射杀了龙,它就死在地上了!)"));
dragonSlayer.goToBattle();
LOGGER.info("Black dragon lands before you.(黑龙在你面前降落。)");
dragonSlayer.changeStrategy(() -> LOGGER.info(
"java8 You cast the spell of disintegration and the dragon vaporizes in a pile of dust!(你施展了瓦解的咒语,龙在一堆尘土中蒸发了!)"));
dragonSlayer.goToBattle();
}
}
/**
* Strategy interface.
*/
@FunctionalInterface
public interface DragonSlayingStrategy {
void execute();
}
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();
}
}
/**
* Melee strategy.
*/
public class MeleeStrategy implements DragonSlayingStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(MeleeStrategy.class);
@Override
public void execute() {
LOGGER.info("With your Excalibur you sever the dragon's head!(你用神剑斩断了龙首!)");
}
}
/**
* Projectile strategy.
*/
public class ProjectileStrategy implements DragonSlayingStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(ProjectileStrategy.class);
@Override
public void execute() {
LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!(你用魔法弩射杀了龙,它就死在地上了!)");
}
}
/**
* Spell strategy.
*/
public class SpellStrategy implements DragonSlayingStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(SpellStrategy.class);
@Override
public void execute() {
LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!(你施展了瓦解的咒语,龙在一堆尘土中蒸发了!)");
}
}
发布评论