Live2D

某大型购物中心欲开发一套收银软件,要求其能够支持购物中心在不同时期推出的各种促销活动,如打折,返利(例如,,满300返100)等等。现采用策略(Strategy)模式实现该要求。代码如下(求修改枚举)

package wy1;
import java.util.*;
enum TYPE1{NORMAL,CASHDISCOUNT,CASHRETURN};

//我本想用枚举型来使用CashContext实体类的switch方法的,不知道为什么主方法中无法实现;
interface CashSuper{
    public double acceptCash(double money);
}

//它定义了一个支付方式的接口,其余支付方式均继承自CashSuper这个接口,底下的支付方式类均使用了这个接口里的方法。

 class CashNormal implements CashSuper
{
public double acceptCash(double money) {
return money;}
}
 class CashDiscount implements CashSuper
{
private double moneyDiscount;
public CashDiscount(double moneyDiscount)
{
this.moneyDiscount=moneyDiscount;    
}
public double acceptCash(double money)
{
return money*moneyDiscount;    
}
}
 class CashReturn implements CashSuper
{
private double moneyCondition;
private double moneyReturn;
public CashReturn(double moneyCondition,double moneyReturn)
{
this.moneyCondition=moneyCondition;
this.moneyReturn=moneyReturn;
}
public double acceptCash(double  money)
{
double result=money;
if(money>=moneyCondition)
    result=money-Math.floor(money/moneyCondition)*moneyReturn;
return result;
}
}
class CashContext{
    private CashSuper cs;
    //private TYPE t;//我在这定义了枚举类的对象,这是我无法实现的地方。
    public CashContext(String t)//本来这个括号里我写着(TYPE t)我就想使用枚举类型。爱爱。
    {
        switch(t) {
        case "正常付账"://上面的枚举类TYPE我没有注释,这本应该时枚举类中的NORMAL,可惜我在主方法中实例化对象时出错。
        cs=new CashNormal();
        break;
        case "超额返利"://同上,这本应该时CashReturn
            cs=new CashReturn(300,100);
            break;
        case "打折扣"://这本应该时CashDiscount的。实例化对象时确失败了,有没人能帮我啊。
            cs=new CashDiscount(0.8);
            break;
        }
    }
    public double GetResult(double money)
    {
        return cs.acceptCash(money);
    }
}
public class Wy1 {

    //private static TYPE NORMAL;

    //private static final TYPE NORMAL = null;

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    CashContext cc=new CashContext("正常付账");//现在我只能把t设置为String类型。无法使用枚举类型。
    double totalPrices=cc.GetResult(500);
    System.out.println(totalPrices);
    cc=new CashContext("超额返利");
    totalPrices=cc.GetResult(500);
    System.out.println(totalPrices);
    cc=new CashContext("打折扣");
    totalPrices=cc.GetResult(500);
    System.out.println(totalPrices);
    
    }

}

参考了https://blog.csdn.net/pnjlc/article/details/52679339, 他的代码有小错误,我想改为枚举型使用但没完成。

posted @ 2018-07-23 20:46  幽香飞狐  阅读(146)  评论(0)    收藏  举报
Live2D