现金收费接口
//现金收费接口
interface CashSuper {
public double acceptCash(double money);
}
正常收费子类
//正常收费子类
public class CashNormal implements CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
打折收费子类
//打折收费子类
public class CashRebate implements CashSuper {
private double moneyRebate=0;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money*moneyRebate;
}
}
返利收费子类 比如满300 反 100
//返利收费子类 比如满300 反 100
public class CashReturn implements CashSuper {
private double moneyCondition=0;
private double moneyReturn=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=money-Math.floor(money/moneyCondition)*moneyReturn;
}
return result;
}
}
Context类
//Context类
public class CashContext {
CashSuper cs = null;
public CashContext(String type) {
String[] arr = new String[] { "正常收费", "满300返100", "打8折" };
int n = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(type)) {
n = i;
}
}
switch (n) {
case 0:
cs = new CashNormal();
break;
case 1:
cs =new CashReturn(300, 100);
break;
case 2:
cs=new CashRebate(0.8);
}
}
public double getResult(double money){
return cs.acceptCash(money);
}
}
客户端类
//客户端类
public class Test {
public static void main(String[] args) {
//CashContext context=new CashContext("正常收费");
//CashContext context=new CashContext("满300返100");
CashContext context=new CashContext("打8折");
double price=100;
int num=10;
double money=price*num;
double lastMoney=context.getResult(money);
System.out.println(lastMoney);
}
}