設計模式之策略模式

概念

接口提供抽象策略方法,由實現類提供具體的策略,並在使用時能總體替換。bash

  • Strategy 策略接口
  • ConcreteStrategy 具體策略實現類
  • Context 上下文 用來選擇具體策略

優勢

  • 策略之間能夠隨意切換
  • 添加新策略只須要新建類,不須要修改原有代碼

缺點

  • 當策略比較多時,也須要較多的實現類

實例

以出行的策略爲例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("上海");
    }
}

結果: 能夠在使用策略時,隨時切換策略。
坐車去。。。北京
坐飛機去。。。上海
複製代碼
相關文章
相關標籤/搜索