在策略模式(Strategy Pattern)中,一個類的行爲或其算法能夠在運行時更改。這種類型的設計模式屬於行爲型模式。算法
在策略模式中,咱們建立表示各類策略的對象和一個行爲隨着策略對象改變而改變的 context 對象。策略對象改變 context 對象的執行算法。設計模式
1.抽象類測試
package strategic; /** * 現金收費抽象類 * @author wuwuyong * */ abstract class CashSuper { public double acceptCash(double money) { return money; } }
2.正常收費子類this
package strategic; /** * 正常收費子類 * @author wuwuyong * */ public class CashNormal extends CashSuper { public double acceptCash(double money) { return money; } }
3.打折收費子類spa
package strategic; /** * 打折收費子類 * @author wuwuyong * */ public class CashRebate extends CashSuper { private double moneyRebate = 1; public CashRebate(Double moneyRebate) { this.moneyRebate = moneyRebate; } public double acceptCash(double money) { return money * this.moneyRebate; } }
4.返利收費子類設計
package strategic; /** * 返利收費子類 * @author wuwuyong * */ public class CashReturn extends CashSuper { private double moneyCondition = 0; private double moneyReturn = 0; public CashReturn(double moneyCondition, double moneyReturn) { this.moneyCondition = moneyCondition; this.moneyReturn = moneyReturn; } public double acceptCash(double money) { double result = money; if (money >= moneyCondition) { result = money - moneyReturn; } return result; } }
5.CashContext3d
package strategic; public class CashContext { private CashSuper cs; public CashContext(String type) { switch (type) { case "正常收費": cs = new CashNormal(); break; case "滿300返100": cs = new CashReturn(300, 100); break; case "打8折": cs = new CashRebate(0.8); break; } } public double getResult(double money) { return cs.acceptCash(money); } }
6.測試code
package strategic; public class Test { public static void main(String[] args) { double result = 0; CashContext normal = new CashContext("正常收費"); result = normal.getResult(300); System.out.println("正常收費:"+result); CashContext cashReturn = new CashContext("滿300返100"); result = cashReturn.getResult(300); System.out.println("滿300返100:"+result); CashContext cashRebate = new CashContext("打8折"); result = cashRebate.getResult(300); System.out.println("打8折:"+result); } }