1.定义
其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
其主要目的是通过定义相似的算法,替换if else 语句写法,并且可以随时相互替换。
2.结构图
- 环境角色(Context):持有一个策略类的引用,提供给客户端使用。
- 抽象策略角色(Strategy):这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
- 具体策略角色(ConcreteStrategy):包装了相关的算法或行为。
3.实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Component public class StrategyUseService implements ApplicationContextAware { private Map<UpgradeWay, Upgrade> upgradeMap = new ConcurrentHashMap<>();
public Long deResolve(UpgradeWay upgradeWay, Long experience) { upgradeWay = Optional.ofNullable(upgradeWay).orElse(UpgradeWay.SLEEP); Upgrade upgrade = upgradeMap.get(upgradeWay); if(upgrade == null) { return null; } return upgrade.resolve(experience); }
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String, Upgrade> beansOfType = applicationContext.getBeansOfType(Upgrade.class); beansOfType.values().forEach(strategyService -> upgradeMap.put(strategyService.gainUpgradeWay(), strategyService)); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public interface Upgrade {
UpgradeWay gainUpgradeWay();
Long resolve(Long experience); }
|
1 2 3 4 5 6 7 8 9 10 11 12
| @Component public class SleepUpgrade implements Upgrade{ @Override public UpgradeWay gainUpgradeWay() { return UpgradeWay.SLEEP; }
@Override public Long resolve(Long experience) { return this.gainUpgradeWay().getValue() + experience; } }
|