定义:
定义一组算法,将每个算法都封装起来,并且使他们之间可以互换。
通用类图如下:
策略模式的优点:
1、算法可以自由切换
2、避免了使用多重条件判断
3、扩展性良好
策略模式的缺点:
所有策略类都需要对外暴露,上层模块必须知道有哪些策略,然后才能决定使用哪个策略,这与迪米特法则是相违背的,可以混合工厂方法模式、代理模式等解决这个缺点。
通用代码如下:
public interface Strategy {
public void doSomething();
}
public class ConcreteStrategy1 implements Strategy {
@Override
public void doSomething() {
System.out.println("strategy 1 is used...");
}
}
public class ConcreteStrategy2 implements Strategy {
@Override
public void doSomething() {
System.out.println("strategy 2 is used...");
}
}
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy=strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void doSomething(){
this.strategy.doSomething();
}
}
public class Client {
public static void main(String[] args) {
Strategy cs1=new ConcreteStrategy1();
Context context=new Context(cs1);
context.doSomething();
Strategy cs2=new ConcreteStrategy2();
context.setStrategy(cs2);
context.doSomething();
}
}