介紹:將具體的算法封裝到獨立的類中,當我們需要使用不同的策略時,只需要給履行對象提供不同的策略就好了。
場景:VR是現在很火的產品,1套好的VR裝備是10分昂貴的,在早期由于市場供不應求,可能買來裝備的價格高于官方報價。過了1段時間,賣家會降價,再過段時間,VR的勢頭過去,堆積的商品會進行促銷。
這個時候我們就能夠使用策略模式,在不同時期,對商品使用不同的價格策略來對價格進行調控。
優點:
- 避免過量使用if-else語句
- 我們只需要在不同時期提供不同策略,使得代碼高內聚低耦合
角色 | 作用 |
---|---|
環境(Context) | 持有1個(Strategy)的援用 |
抽象策略(Strategy) | 定義所有的具體策略類所需的實現的方法 |
具體策略(ConcreteStrategy) | 實現具體方法,定義方法中的具體算法 |
策略基類
提供降價接口
public interface Strategy {
public double offerPrice(double orgPrice);
}
小幅度降價:打8折
public class DepreciateStrategy implements Strategy {
@Override
public double offerPrice(double orgPrice) {
System.out.println("現在商品小降價");
return .8 * orgPrice;
}
}
提價:供不應求.為原價的1.2倍
public class RaiseStrategy implements Strategy {
@Override
public double offerPrice(double orgPrice) {
System.out.println("現在商品抬價");
return 1.2 * orgPrice;
}
}
促銷價:為原價的1半
public class PromotionStrategy implements Strategy {
@Override
public double offerPrice(double orgPrice) {
System.out.println("現在商品促銷價");
return .5 * orgPrice;
}
}
VR裝備:環境類
public class VR {
public double orgPrice = 10000.0; // 商品官方的報價
private Strategy strategy;
public VR(Strategy strategy) {
this.strategy = strategy;
}
public double getPrice() {
return strategy.offerPrice(orgPrice);
}
}
場景利用
public static void main(String[] args) {
Strategy sg1 = new RaiseStrategy();
VR vr1 = new VR(sg1);
System.out.println(vr1.getPrice());
Strategy sg2 = new DepreciateStrategy();
VR vr2 = new VR(sg2);
System.out.println(vr2.getPrice());
Strategy sg3 = new PromotionStrategy();
VR vr3 = new VR(sg3);
System.out.println(vr3.getPrice());
}
輸出
現在商品抬價
12000.0
現在商品小降價
8000.0
現在商品促銷價
5000.0
在網上學習其他大神博客的時候看到很多評論,這不是狀態模式是策略模式,或這不是策略模式是狀態模式,不要誤人子弟。但是其實博主是正確的,而那些言語粗魯的人反而是自己無知(讓我10分反感)。狀態模式常常與策略模式相混淆。1個簡單的方法是考察環境角色是不是有明顯的狀態和狀態的過渡。
狀態模式:
狀態模式處理的核心問題是狀態的遷移,由于在對象存在很多狀態情況下,各個狀態之間跳轉和遷移進程都是及其復雜的。在狀態模式中,狀態改變是由對象的內部條件決定,外界只需關心其接口,沒必要關心其狀態對象的創建和轉化。
策略模式:
策略模式的好處在于你可以動態的改變對象的策略行動。策略模式里,采取何種策略由外部條件決定,也就是說使用甚么策略由我們來提供,而策略的具體實現類實現對應算法。比如1種商品,我們可以有很多降價和提價策略,我們只需要定義好各種策略的規則,然后讓商品去履行就好了。
更多模式:http://blog.csdn.net/odeviloo/article/details/52382338
更多源碼:https://github.com/oDevilo/Java-Base
下一篇 libusb的異步也有這樣的問題