圖解設計模式(11) 策略模式

一、 應用場景

    商場對於不同的客戶採用不同的打折策略;

    施工對於不同的地形地貌採用不同的施工方法;數據處理針對不同批量的數據選取不同的算法等。

    對於常用的

    if() {

    }else if(){

    }else if(){

    }else{}

    結構,可以採用策略模式來重構。 當增加新的模式時,不需要修改原有的代碼,符合開閉原則。

    它可以算法與架構分離。

 

二、具體實現

  •     實現要點

1. 一個Strategy interface, 在其中定義要實現的方法。

2. 多個具體的Strategy類,implements interface, 在其中實現不同的算法。

3.一個上下文類 Context, 其中包含Strategy 對象,可以選擇不同的具體策略類來處理業務。

  •     代碼實現

以超市打折策略爲例,新客戶買的少不打折;新客戶買的多打9折;老客戶買的少打9折;老客戶買的多打8折。

 1. Strategy接口,規定要實現的方法。

public interface Strategy {
    double getPrice(double originalPrice);
}

2. 不同的策略, implements interface

public class NewCustomerFew implements Strategy {

    @Override
    public double getPrice(double originalPrice) {
        System.out.println("新客戶買的少不打折!");
        return originalPrice;
    }
}

class NewCustomerMany implements Strategy {

    @Override
    public double getPrice(double originalPrice) {
        System.out.println("新客戶買的多打九折!");
        return originalPrice * 0.9;
    }
}

class OldCustomerFew implements Strategy {

    @Override
    public double getPrice(double originalPrice) {
        System.out.println("老客戶買的少打九折!");
        return originalPrice * 0.9;
    }
}

class OldCustomerMany implements Strategy {

    @Override
    public double getPrice(double originalPrice) {
        System.out.println("老客戶買的多打八折!");
        return originalPrice * 0.8;
    }
}

3. 上下文類,包含有策略的對象。

public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public double getPrice(double originalPrice){
        return this.strategy.getPrice(originalPrice);
    }
}

測試類

public class ClientTest {

    public static void main(String[] args) {
        Context context = new Context(new NewCustomerFew()); //新客戶買的少
        System.out.println(context.getPrice(100));
        
        context.setStrategy(new OldCustomerMany());  //老客戶買的多
        System.out.println(context.getPrice(999));
    }
}

測試結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章