java 策略模式-2015下半年軟考-設計模式

商店有三種策略[原價、打折、滿減]java

//枚舉三種策略
enum TYPE {NORMAL,CASH_DISCOUNT,CASH_RETURN}

interface CashSuper{
    public double acceptCash(double money);    
}

//原價
class CashNormal implements CashSuper{
    public double acceptCash(double money){
        return money;
    }
}

//打折
class CashDiscount implements CashSuper{
    private double discountRate;

    public CashDiscount(double discountRate){
        this.discountRate=discountRate;
        
    }
    public double acceptCash(double money){
        return money*discountRate;
    }
}

//滿減
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-moneyReturn;
        }
        return result;
    }
}
public class CashContent {
    private CashSuper sc;
    private TYPE t;
    
    public CashContent (TYPE t){
            switch (t){
            case NORMAL:
            sc=new CashNormal();
            break;
            
            case CASH_DISCOUNT:
            sc=new CashDiscount(0.9);
            break;
            
            
            case CASH_RETURN:
            sc=new CashReturn(300.00,50.00);
            break;
        
        }
        
        
    }
    
//實現
    public static void main(String[] argus){
        CashContent cc=new CashContent(TYPE.CASH_RETURN);
        //CashContent cc=new CashContent(TYPE.CASH_DISCOUNT);
        //CashContent cc=new CashContent(TYPE.NORMAL);
        
        System.out.println(cc.sc.acceptCash(900));//結果爲900-50=850.0
        
    }
}
相關文章
相關標籤/搜索