前面我們講了設計模式中的工廠模式,今天我們來學習下策略模式。工廠模式,顧名思義就是生產“產品”的地方,以“生產”爲主。策略模式其實就是封裝算法的地方,在生活當中我們可能會遇到這麼一種情況,在不同的時間或地點執行不同的規則。比如,超市裏面會根據不同的節假日進行打折,買滿200立減100,積分兌換等活動,那麼針對這種情況我們如何來適應這種規則的變化呢?這就是我們今天要講的策略模式。下面我們來模擬一個收銀系統:
收銀系統通常分如下幾種情況:
1、正常收費
2、打折收費
3、買滿指定金額商品後減X元
4、積分兌換
首頁,定義一個接口IStrategy讓這4種“規則”的類來實現
public interface IStrategy { public abstract void strategy(); }
接下來的4種類分別實現,如下:
public class NormalStrategy implements IStrategy { @Override public void strategy() { // TODO Auto-generated method stub System.out.println("正常收費"); } } public class RotateStrategy implements IStrategy { @Override public void strategy() { // TODO Auto-generated method stub System.out.println("折扣收費"); } } public class ReturnStrategy implements IStrategy { @Override public void strategy() { // TODO Auto-generated method stub System.out.println("滿300減50收費"); } } 用一個Context類來維護這個規則配置,代碼如下: public class Context { public int type; public IStrategy strategy; public Context(int t) { this.type = t; } public void performStrategy() { strategy = StrategyFactory.makeStrategy(type); this.strategy.strategy(); } }
public class MyStrategy
{
public static void main(String[] args)
{
Context context = null;
context = new Context(1);
context.performStrategy();
context = new Context(2);
context.performStrategy();
context = new Context(3);
context.performStrategy();
}
}