接口提供抽象策略方法,由實現類提供具體的策略,並在使用時能總體替換。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("上海");
}
}
結果: 能夠在使用策略時,隨時切換策略。
坐車去。。。北京
坐飛機去。。。上海
複製代碼