package com.design.utils;
import org.junit.Test;
public class TestStrategy {
/*
* 现金收取抽象类(Strategy类)
*/
abstract class CashSuper {
public abstract double acceptCash(double money);
}
/*
* 正常收取子类(ConcreteStategy类)
*/
class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
/*
* 打折收取子类(ConcreteStategy类)
*/
class CashRebate extends CashSuper {
private double moneyRebate = 1;
CashRebate(String moneyRebate) {
this.moneyRebate = Double.parseDouble(moneyRebate);
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
/*
* 返利收取子类(ConcreteStategy类)
*/
class CashReturn extends CashSuper {
private double moneyCondition = 0;
private double moneyReturn = 0;
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;
}
}
/*
* CashContext类维护CashSuper对象的引用
*/
class CashContext{
CashSuper cs = null;
CashContext(String type){
switch (type) {
case "正常收费":
cs = new CashNormal();
break;
case "打8折":
cs = new CashRebate("0.8");
break;
case "满300减100":
cs = new CashReturn("300", "100");
break;
}
}
public double GetResult(double money){
return cs.acceptCash(money);
}
}
/*
* 测试
*/
@Test
public void testStrategy(){
//应收金额
double price = 1222;
//促销类型
String type = "打8折";
CashContext cc = new CashContext(type);
System.out.println("实收金额:" + cc.GetResult(price));
}
}
策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要再不同时间应用不同的业务规则,就可以考虑策略模式处理这种变化的可能性。