import java.text.DecimalFormat;
/**
- @Author: cxh
- @CreateTime: 18/1/1 12:04
- @ProjectName: JavaBaseTest
- 客户端:测试
*/
public class Client {
public static void main(String[] args) {
double result=0;
int flag=0;//0,1,2,3代表:正常价格 ;七折; 满100减去5; 积分抵扣现金
ContextStrategyRef cs;
for(int i=10;i<60;i+=10){
if(flag==0){
cs=new ContextStrategyRef("正常收费");
result+=cs.getSum(i);
flag++;
continue;
}else if(flag==1){
cs=new ContextStrategyRef("折扣7折");
result+=cs.getSum(i);
flag++;
continue;
}else if(flag==2){
cs=new ContextStrategyRef("满100减5");
result+=cs.getSum(i);
flag++;
}else if(flag==3){
cs=new ContextStrategyRef("1000积分抵扣1元");
result+=cs.getSum(i);
flag=0;
}
}
//保留2位小数
DecimalFormat df=new DecimalFormat("#.00");
System.out.println(df.format(result));
}
}<span style="text-align:justify;"> <span style="text-align:justify;"> <span style="text-align:justify;"> <span style="text-align:justify;"> <span style="text-align:justify;">
/**
- @Author: cxh
- @CreateTime: 18/1/1 11:20
- @ProjectName: JavaBaseTest
*/
public class Strategy {
public double getRealMoney(double money){
return -1D;
}
}
/**
-
@Author: cxh
-
@CreateTime: 18/1/1 11:21
-
@ProjectName: JavaBaseTest
-
打折策略类
*/
public class StrategyA extends Strategy {
private double discount;//折扣
public StrategyA(double discount){
this.discount=discount;
}
//获取折扣后的金额
@Override
public double getRealMoney(double money) {
return money*discount;
}
}
/**
-
@Author: cxh
-
@CreateTime: 18/1/1 11:25
-
@ProjectName: JavaBaseTest
-
满减 类
*/
public class StrategyB extends Strategy {
private int condition,mongeyReturn;
public StrategyB(int condition,int mreturn){
this.condition=condition;
this.mongeyReturn=mreturn;
}
@Override
public double getRealMoney(double money) {
if(money>=condition)
return money-mongeyReturn;
else
return money;
}
}
/**
- @Author: cxh
- @CreateTime: 18/1/1 11:38
- @ProjectName: JavaBaseTest
- 积分抵扣现金 类
/
public class StrategyC extends Strategy {
@Override
public double getRealMoney(double money) {
//积分得从账户获取,所以这里就用一个[1,10]的随机数字代表
return money-10Math.random();
}
}
/**
-
@Author: cxh
-
@CreateTime: 18/1/1 11:45
-
@ProjectName: JavaBaseTest
*/
public class ContextStrategyRef {
private Strategy strategy;//保持对 促销策略的引用.
//构造函数,确定实例化哪一个类
public ContextStrategyRef(String selectedItem){
switch (selectedItem){
case "正常收费":
strategy=new StrategyA(1);
break;
case "折扣7折":
strategy=new StrategyA(0.7);
break;
case "满100减5":
strategy=new StrategyB(100,5);
break;
case "1000积分抵扣1元":
strategy=new StrategyC();
}
}
public double getSum(double money){
return strategy.getRealMoney(money);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。