策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
一、需求
实现一个商场收银软件,满足满减、打折、正常收费。
二、代码实现
封装策略
public class CashContext { private CashSuper cs; public CashContext(int cashType) { CashSuper cs = null; switch (cashType) { case 1: cs = new CashNormal(); break; case 2: cs = new CashRebate(0.8d); break; case 3: cs = new CashRebate(0.7d); break; case 4: cs = new CashReturn(300d, 100d); break; } } public double getResult(double price, int num) { return this.cs.acceptCash(price, num); } }
策略实现
//收费抽象类 public abstract class CashSuper { /** * 收取费用 */ public abstract double acceptCash(double price,int num); } public class CashNormal extends CashSuper{ //原价返回 @Override public double acceptCash(double price, int num) { return price*num; } } //打折收费 public class CashRebate extends CashSuper { //费率 private double moneyRebate = 1d; //初始化费率 public CashRebate(double moneyRebate) { this.moneyRebate = moneyRebate; } @Override public double acceptCash(double price, int num) { return price * num * this.moneyRebate; } } //满减 public class CashReturn extends CashSuper { //返利条件 private double moneyCondition = 0d; //返利值 private double moneyReturn = 0d; //返利收费。初始化时需要输入返利条件和返利值。 // 比如“满300返100”,就是moneyCondition=300,moneyReturn=100 public CashReturn(double moneyCondition, double moneyReturn) { this.moneyCondition = moneyCondition; this.moneyReturn = moneyReturn; } //计算收费时,当达到返利条件,就原价减去返利值 @Override public double acceptCash(double price, int num) { double result = price * num; if (moneyCondition > 0 && result >= moneyReturn) { result = result - Math.floor(result / moneyCondition) * moneyReturn; } return result; } }
public static void main(String[] args) { double price = 20d; int num = 50; //策略模式与简单工厂模式结合 double result2 = new CashContext(1).getResult(price, num); }