策略模式(strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
理念:封装变化点,在不同时间应用不同的业务规则。
如:商场中促销,打折,返利,积分,都是一种促销模式,针对这些促销,可以指定对应的策略。
策略模式设计图
场景:
针对商场中不同的促销产生不同的策略
使用策略+简单工厂实现
java代码实现
//主函数
public class StrategyTest {
public static void main(String[] args) {
double money = 400;
//正常收费
CashContext context = new CashContext("正常收费");
System.out.println("正常收费:" + context.getResult(money));
//打折
context = new CashContext("打折");
System.out.println("正常收费:" + context.getResult(money));
//返利
context = new CashContext("返利");
System.out.println("正常收费:" + context.getResult(money));
}
}
//现金上下文(类似工厂作用)
public class CashContext {
CashSuper cashSuper;
public CashContext(String type) {
switch (type) {
case "正常收费":
cashSuper = new CashNormal();
break;
case "打折":
cashSuper = new CashRebate(0.8);
break;
case "返利":
cashSuper = new CashReturn(300, 100);
break;
}
}
public double getResult(double money) {
return cashSuper.acceptCash(money);
}
}
//策略的抽象类
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
//正常收费策略
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
//打折收费策略
public class CashRebate extends CashSuper {
public double discount;
public CashRebate(double discount) {
this.discount = discount;
}
@Override
public double acceptCash(double money) {
return money * discount;
}
}
//返利收费策略
public class CashReturn extends CashSuper {
public double moneyCondition = 0.0;
public double moneyReturn = 0.0;
public CashReturn(double moneyCondition, double moneyReturn){
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
double result = money;
if (money > moneyCondition){
result = result - (int)(money / moneyCondition) * moneyReturn;
}
return result;
}
}
存在的问题,如果新增促销策略,需要在工厂的switch里添加代码,可以使用反射优化