1. 程式人生 > >策略模式-商場促銷-大話設計模式 .

策略模式-商場促銷-大話設計模式 .

類結構:

//父類,商場結賬的演算法
public interface SuperCash {
	//得到算過後的結賬金額
	public double getcash(double cash);
}



//正常的結賬
public class NormalCash implements SuperCash{

 public double getcash(double cash) {
  return cash;
 }

}


//對購買的貨物進行打折的結賬方式
public class DiscountCash implements SuperCash{
	private float moneyRebate;//打折的折扣
	public DiscountCash(float moneyRebate){
		this.moneyRebate=moneyRebate;
	}
	public double getcash(double cash) {
		return moneyRebate*cash;
	}

}


//買五百送三百的這種方式結賬
public class ReturnCash implements SuperCash{
	private float upcash;//五百
	private float downcash;//三百
	public ReturnCash(float upcash,float downcash){
		this.upcash=upcash;
		this.downcash=downcash;
	}
	public double getcash(double cash) {
		double result=cash;
		if(cash>=upcash){
			result=cash-(Math.floor(cash/upcash)*downcash);
		}
		return result;
	}
}


//演算法選擇,並輸出結果
public class CashContext {
	private SuperCash supercash;
	public CashContext(String type){
		//超市收款用多個演算法類來進行使用和選擇
		if("正常收費".equals(type)){
			
			supercash=new NormalCash();
		}else if(type.matches("打.+折")){
			
			float cash=Float.parseFloat(type.replaceAll("打(.+)折", "$1"));
			supercash=new DiscountCash(cash/10);
		}else if(type.matches("滿.+送.+")){
			
			float cashup=Float.parseFloat(type.replaceAll("滿(.+)送.+", "$1"));
			float cashdown=Float.parseFloat(type.replaceAll("滿.+送(.+)", "$1"));
			supercash=new ReturnCash(cashup,cashdown);
		}
	}
	public double getResult(double cash){
		return supercash.getcash(cash);
	}
}


public class Test {
	//策略模式:策略封裝了變化
	//也就是超市收款用多個演算法類來進行使用和選擇
	public static void main(String[] args) {
//		String type="正常收費";//輸出:400.0
//		String type="打8折";//輸出:320.0000047683716
		String type="滿150送50";//輸出:300.0
		CashContext context = new CashContext(type);
		double cash=context.getResult(400);
		System.out.println(cash);
	}
}