概念
接口提供抽象策略方法,由实现类提供具体的策略,并在使用时能整体替换。
- Strategy 策略接口
- ConcreteStrategy 具体策略实现类
- Context 上下文 用来选择具体策略
优点
- 策略之间可以随意切换
- 添加新策略只需要新建类,不需要修改原有代码
缺点
- 当策略比较多时,也需要较多的实现类
实例
以出行的策略为例
- 抽象策略
这里也可以用抽象类
/**
* 策略接口
* 提供到达目的地方法,具体怎么去由子类实现
* @author by peng
* @date in 2019-06-14 23:31
*/
public interface ITransportable {
/**
* 到达目的地
*/
void toDestination(String destination);
}
- 具体策略
public class Car implements ITransportable {
@Override
public void toDestination(String destination) {
System.out.println("坐车去。。。" + destination);
}
}
public class Plane implements ITransportable {
@Override
public void toDestination(String destination) {
System.out.println("坐飞机去。。。" + destination);
}
}
- 执行策略的类
public class Person {
private ITransportable transportable;
public void setTransportable(ITransportable transportable){
this.transportable = transportable;
}
public void travel(String destination){
transportable.toDestination(destination);
}
}
- 测试
public class Test {
public static void main(String... arg){
Person ming = new Person();
ming.setTransportable(new Car());
ming.travel("北京");
ming.setTransportable(new Plane());
ming.travel("上海");
}
}
结果: 可以在使用策略时,随时切换策略。
坐车去。。。北京
坐飞机去。。。上海