开发过程中,需要根据不同场景选择不同算法和策略。
将需要经常改变的部分抽象提取为接口,通过引用该接口,就可以调用该接口实现类的行为,即具体策略。实现了策略具体实现和调用者的隔离。
优点
- 可以动态改变对象行为
缺点
- 使用哪种策略需要调用者自己决定
- 产生很多策略类
示例
public interface IStrategy {
public void doSomething();
}
public class Strategy1 implements IStrategy {
@Override
public void doSomething() {
}
}
public class Strategy2 implements IStrategy {
@Override
public void doSomething() {
}
}
public class Context implements IStrategy {
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy = strategy;
}
@Override
public void doSomething() {
strategy.doSomething();
}
}
public static void main(String[] args) {
IStrategy strategy = new Strategy1();
Context context = new Context(strategy);
context.doSomething();
}