策略模式封装了变化。
标准策略模式:
/** * Created by hero on 16-3-29. */ public abstract class CashSuper { public abstract double acceptCash(double money); } /** * Created by hero on 16-3-29. */ public class CashNormal extends CashSuper{ @Override public double acceptCash(double money) { return money; } } /** * Created by hero on 16-3-29. */ public class CashRebate extends CashSuper { private double moneyRebate = 1d; public double getMoneyRebate() { return moneyRebate; } public void setMoneyRebate(double moneyRebate) { if (moneyRebate < 0) { throw new IllegalArgumentException("what's wrong with this supermarket?!!!"); } this.moneyRebate = moneyRebate; } public CashRebate(double moneyRebate) { this.setMoneyRebate(moneyRebate); } @Override public double acceptCash(double money) { return getMoneyRebate() * money; } } /** * Created by hero on 16-3-29. */ public class CashContext { private CashSuper cashSuper = null; public CashContext(CashSuper cashSuper) { this.cashSuper = cashSuper; } public double getResult(double money) { return cashSuper.acceptCash(money); } } public class Main { public static void main(String[] args) { CashContext cashContext = null; cashContext = new CashContext(new CashNormal()); System.out.println(cashContext.getResult(12)); cashContext = new CashContext(new CashRebate(0.3)); System.out.println(cashContext.getResult(12)); } }
策略与简单工厂结合:
简单工厂模式对类似“满300减200、满400减100”的变化进行有效封装,除非另外制定一套规则比如:“满减-400,100、满减-500,100”,在swich语句中只取‘-’之前的作case条件,其后跟参数,多个参数以
‘,’分割。
策略与简单工厂的结合使后端对前端的暴露降低了。算是集成了二者的优点吧。