策略模式
Strategy Pattern
定义:
Define a family of algorithms,encapsulate each one,and make them interchangeable.
定义一组算法 ,把每个算法都封装起来,使他们可以相互切换
因为每个算法
都是实现于同个接口的,那么他们肯定能相互切换的
定义角色:
- Context 封装角色: 也叫上下文角色。起承上启下的作用,屏蔽高策模块对策略、算法的直接访问。
- Strategy 抽象策略角色:通常为一个接口。定义了每个策略必须具备的方法或者属性。
- ConcreteStrategy 具体策略角色
通用代码:
抽象策略角色
public interface Strategy {
public void doSomething();
}
具体策略角色
public class ConcreteSrategy1 implements Strategy {
public void doSomethis() {
....
}
}
public class ConcreteSrategy2 implements Strategy {
public void doSomethis() {
....
}
}
封装角色
public class Context {
private Strategy strategy = null;
public Context(Strategy strategy) {
this.strategy = strategy;
}
//封装策略方法
public void doAnything() {
this.strateg.doSomething();
}
}
场景调用
public class Client {
public static void main(String[] args) {
//声明一个具体策略
Strategy strategy = new ConcreteStrategy1();
//声明上下文对象
Context context = new Context(strategy);
//执行封装后的方法
context.doAnything();
}
}
策略模式的重点就是封装角色,它借用的是代理模式的思路,与代理模式的的差别是策略模式的封装角色和被封装角色的策略类用的不是用一个接口,如果用的是同一个接口就是代理模式了。
优点
- 对外可以自由切换策略
- 避免多重条件判断
- 扩展性高
缺点
- 具体策略的数量增多
- 所有策略类都要对外暴露,因为高层模块需要知道有哪些策略
应用:
- 当一个策略族的具体策略类的数量超过4个,就需要考虑使用混合模式来解决策略类膨胀和对外暴露的问题。
- 一般都是混合工厂方法模式来实现对策略类的声明