策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
package strategy;
/**
* 策略模式(Strategy)
* 现金收费抽象类
*/
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
package strategy;
/**
* 策略模式(Strategy)
* 正常收费子类
*/
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
package strategy;
/**
* 策略模式(Strategy)
* 打折收费子类
*/
public class CashRebate extends CashSuper {
private double moneyRebate = 1.0;
public CashRebate(String moneyRebate) {
this.moneyRebate = Double.parseDouble(moneyRebate);
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
package strategy;
/**
* 策略模式(Strategy)
* 返利收费子类
*/
public class CashReturn extends CashSuper {
// 满多少
private double moneyCondition = 1.0;
// 返多少
private double moneyReturn = 1.0;
public CashReturn(String moneyCondition, String moneyReturn) {
this.moneyCondition = Double.parseDouble(moneyCondition);
this.moneyReturn = Double.parseDouble(moneyReturn);
}
@Override
public double acceptCash(double money) {
double result = money;
if (money >= moneyCondition) {
result = money - Math.floor(money / moneyCondition) * moneyReturn;
}
return result;
}
}
package strategy;
/**
* 策略模式(Strategy)
* Cash上下文
*/
public class CashContext {
CashSuper cs = null;
public CashContext(String type) {
switch (type) {
case "正常收费":
CashNormal c0 = new CashNormal();
cs = c0;
break;
case "满300返100":
CashReturn c1 = new CashReturn("300", "100");
cs = c1;
break;
case "打8折":
CashRebate c2 = new CashRebate("0.8");
cs = c2;
break;
}
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
package strategy;
/**
* 策略模式(Strategy)
* 客户端main方法
*/
public class CashClient {
public static void main(String[] args) {
CashContext context = new CashContext("正常收费");
double money0 = context.getResult(300);
System.out.println("正常收费: " + money0);
context = new CashContext("打8折");
double money1 = context.getResult(300);
System.out.println("打8折: " + money1);
context = new CashContext("满300返100");
double money2 = context.getResult(300);
System.out.println("满300返100: " + money2);
}
}