接口提供抽象策略方法,由实现类提供具体的策略,并在使用时能总体替换。bash
以出行的策略为例ide
这里也能够用抽象类
/**
* 策略接口
* 提供到达目的地方法,具体怎么去由子类实现
* @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("上海");
}
}
结果: 能够在使用策略时,随时切换策略。
坐车去。。。北京
坐飞机去。。。上海
复制代码