定义:
- 定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。
通用类图:
策略模式通用类图
/*
* 抽象的策略模式
* */
public abstract class Strategy {
abstract void doSomething();
}
/*
* 定义具体的策咯模式
* */
public class ConcreteStrategyOne extends Strategy {
@Override
void doSomething() {
// TODO Auto-generated method stub
}
}
public class ConcreteStrategyTwo extends Strategy {
@Override
void doSomething() {
// TODO Auto-generated method stub
}
}
/*
* 定义上下文角色,用来封装对象
* */
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
// TODO Auto-generated constructor stub
this.strategy = strategy;
}
public void doAnything() {
this.strategy.doSomething();
}
}
public class Client {
public static void main(String[] args) {
Strategy strategyOne = new ConcreteStrategyOne();
Context context = new Context(strategyOne);
context.doAnything();// 高层模块实现对底层算法模块细节的屏蔽
}
}
优点:
- 算法可以自由切换
- 避免本身实现多重条件的判断,由外部条件决定当前应该使用哪一种算法
- 拓展性良好
缺点:
- 策略类数量增多
- 所有的策略类都需要对外暴露