策略模式

1.定义

其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
其主要目的是通过定义相似的算法,替换if else 语句写法,并且可以随时相互替换。

2.结构图

img

  • 环境角色(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);
}


// spring初始化初始化时候即初始化各种策略
@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 {
/**
* 获取策略类型
* @return 策略类型
*/
UpgradeWay gainUpgradeWay();

/**
* 具体实现逻辑
* @param experience 原有经验值
*/
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;
}
}