策略模式(Strategy Pattern)
定义:
Define a family of algorithms, encapsulate each one, andmake them interchangeable.
定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。
类图:暂时忽略,百度都有。(等我能上传图了,我会补上)
从类图可以看出其主要包含三个功能类
- Context 上下文类
- Strategy抽象策略类
- ConcreteStrategy具体策略类
优点
- 算法之间自由切换
- 避免写if···else的语句
- 可扩展性
缺点
- 类的数量较多,当策略类过多时,维护起来不方便
用例代码如下:
public interface Strategy {
public void doSomething();
}
public class Context {
private Strategy strategy = null;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void doAnythinig() {
this.strategy.doSomething();
}
}
public class ConcreteStrategy2 implements Strategy {
public void doSomething() {
System.out.println("执行策略2");
}
}
public class ConcreteStrategy1 implements Strategy {
public void doSomething() {
System.out.println("执行策略1");
}
}
测试类
public class Test {
public static void main(String[] args) {
Strategy strategy = new ConcreteStrategy1();
Context context = new Context(strategy);
context.doAnythinig();
context=new Context(new ConcreteStrategy2());
context.doAnythinig();
}
}
输出结果
执行策略1
执行策略2