策略模式
定义
Define a family of algorithms , encapsulate each one , and make them interchangeable.
定义一组算法,将每个算法封装起来,并且使它们之间可以互换。
策略模式示意图
![策略模式]()
流程
- 定义一个总的策略接口,所有的具体策略都要实现这个接口,因为这些策略都有相同的目标。
- 将策略封装进策略上下文,让策略有完整的过程。
- 客户直接就使用这个完整的过程。
代码实现
策略
- 策略总接口
1 2 3 4 5 6 7
|
public interface IStrategy { public void strategy(); }
|
- 实现总接口的具体策略1
1 2 3 4 5 6 7
| public class Strategy1 implements IStrategy { @Override public void strategy() { System.out.println("策略1"); } }
|
- 实现总接口的具体策略2
1 2 3 4 5 6 7
| public class Strategy2 implements IStrategy{ @Override public void strategy() { System.out.println("策略2"); } }
|
- 实现总接口的具体策略3
1 2 3 4 5 6 7
| public class Strategy3 implements IStrategy { @Override public void strategy() { System.out.println("策略3"); } }
|
封装
将策略进行封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class Context { private IStrategy strategy ;
public IStrategy getStrategy(){ return strategy ; }
public void setStrategy(IStrategy strategy){ this.strategy = strategy ; }
public void executeStrategy(){ System.out.println("策略开始执行"); strategy.strategy(); System.out.println("策略执行完成"); } }
|
场景实现
1 2 3 4 5 6 7 8 9 10 11 12
| public class Test{ public static void main(String[] args) { IStrategy strategy1 = new Strategy1(); Context context = new Context(); context.setStrategy(strategy1); context.executeStrategy(); } }
|
应用场景
- 多个类只有在算法或行为上稍有不同的场景。
- 算法需要自由切换。
- 需要屏蔽算法规则。
- 如果具体策略数量大于3个,可以考虑使用混合模式。
策略模式的优缺点
优点
- 策略算法可以自由切换
- 避免使用多重条件判断,我们有这么多策略,不需要使用判断语句来判断需要使用哪种策略,我们这是被动选择策略。我们可以使用多态来,我们主动选择策略。
- 扩展性好,我们可以随时添加一个策略而不用改任何代码。
缺点
- 每个策略类就是一种策略,具体策略类不能被复用,这样策略变多,会显得很臃肿。
- 我们需要创建具体策略对象,这样所有的策略类都会向对外暴露,违反了迪米特法则。