package strategy; public abstract class CashSuper { // 现金收费抽象类 public abstract double acceptCash(double money); }
package strategy; public class CashRebate extends CashSuper { private double moneyRebate = 1; // 打折收费类 默认1 既是不打折 public CashRebate(double moneyRebate) { this.moneyRebate = moneyRebate; } @Override public double acceptCash(double money) { return money * moneyRebate; } }
package strategy; 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; } //我的理解是达到满300返利100,满600返利250,这种情况的 @Override public double acceptCash(double money) { double result = money; if (money >= moneyCondition) { result = money - moneyReturn; } return result; } }
package strategy; public class CashContext { private CashSuper cs; public CashContext(String type) { switch (type) { case "打折": CashRebate cs0=new CashRebate(0.8); cs=cs0; break; case "满300返100": CashReturn cr1=new CashReturn(300, 100); cs=cr1; break; } } public double GetResult(double money){ return cs.acceptCash(money); } }
package strategy; public class Test { public static void main(String[] args) { double total=0; CashContext csuper=new CashContext("打折"); double money=100; total=csuper.GetResult(money); System.out.println(total); } }
感觉策略模式和简单工厂差不多的样子,一个工厂类用静态方法类传参生成对象,一个用构成方法传参数生成对象。
个人倾向于静态方法类传参生成对象,没必要的对象可以不用生成。