package strategy;
//嵌入策略
public class CashContext {
private Cash cs;
public CashContext(Cash cs) {
super();
this.cs = cs;
}
public double getResult(double money){
return cs.acceptCash(money);
}
}
package strategy;
public interface Cash {
public abstract double acceptCash(double money);
}
package strategy;
/*
* 正常收费
*/
public class CashNormal implements Cash{
@Override
public double acceptCash(double money) {
return money;
}
}
package strategy;
/*
* 打折策略
*/
public class CashRebate implements Cash{
private double moneyRebate;
public CashRebate() {
super();
}
public CashRebate(double moneyRebate) {
super();
this.moneyRebate = moneyRebate;
}
public double getMoneyRebate() {
return moneyRebate;
}
public void setMoneyRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money*moneyRebate;
}
}
package strategy;
/*
* 返利收费策略
*/
public class CashReturn implements Cash {
private double moneyCondition;
private double moneyReturn;
public CashReturn() {
super();
}
public CashReturn(double moneyCondition, double moneyReturn) {
super();
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
public double getMoneyCondition() {
return moneyCondition;
}
public void setMoneyCondition(double moneyCondition) {
this.moneyCondition = moneyCondition;
}
public double getMoneyReturn() {
return moneyReturn;
}
public void setMoneyReturn(double moneyReturn) {
this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
if(money>=moneyCondition){
return money-(int)(money/moneyCondition)*moneyReturn;
}
return money;
}
}
测试类:
package strategy;
import java.util.Scanner;
/*
* 测试代码
*/
public class test {
public static void main(String[] args) {
CashContext cc=null;
double moneyRebate=0;
double money=0;
Scanner sc= new Scanner(System.in);
System.out.println("请输入折扣类型");
String type = sc.next();
switch (type) {
case "正常收费":
cc=new CashContext(new CashNormal());
break;
case "打折":
System.out.println("请输入打折比例");
moneyRebate=sc.nextDouble();
cc=new CashContext(new CashRebate(moneyRebate));
break;
case "返利":
cc=new CashContext(new CashReturn(500, 50));
break;
}
System.out.println("请输入金额");
money = sc.nextDouble();
System.out.println(cc.getResult(money));
}
}
时间: 2024-10-11 21:33:57