我看的是《大话设计模式》中的策略模式的介绍,下面是代码实现,做个记录。
首先是一个抽象的策略定义以及三个具体的实现。
public interface Cash {
/**
* 计算现金,输入原价,返回现价
* @param money
* @return
*/
double acceptCash(double money);
}
//正常收费
public class CashNormal implements Cash{
@Override
public double acceptCash(double money) {
return money;
}
}
//打折收费
public class CashRebate implements Cash{
private double moneyRebate = 1d;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
//返利收费
public class CashReturn implements Cash{
private double moneyCondition;
private double moneyReturn;
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 = money - Math.floor(money/moneyCondition) * moneyReturn;
}
return result;
}
}
然后就是将策略模式与简单工厂结合的策略上下文:
/**
* 策略上下文,用于封装变化点
*/
public class CashContext {
private Cash cash = null;
public CashContext(String type){
switch (type){
case "正常收费":
cash = new CashNormal();
break;
case "打八折":
cash = new CashRebate(0.8);
break;
case "满300返100":
cash = new CashReturn(300,100);
break;
}
}
public double getResult(double money){
return cash.acceptCash(money);
}
}
最后就是客户端测试:
public class Client {
public static void main(String[] args) {
CashContext cashContext = new CashContext("正常收费");
double result = cashContext.getResult(300);
System.out.println(result);
cashContext = new CashContext("打八折");
result = cashContext.getResult(300);
System.out.println(result);
cashContext = new CashContext("满300返100");
result = cashContext.getResult(300);
System.out.println(result);
}
}