package com.strategy;
/**
* 現金收取類
* @author Administrator
*
*/
public interface CashSuper {
/**
*
* @param money 收取現金,引數為原價,返回當前價
* @return
*/
public double acceptCash (double money);
}
package com.strategy;
/**
* 正常收費 ,不參加任何活動。
* @author Administrator
*
*/
public class CashNormal implements CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
package com.strategy;
/**
* 打折收費
* @author Administrator
*
*/
public class CashRebate implements CashSuper {
private double moneyRebate = 1;
public CashRebate (String rebate ){
this.moneyRebate =Double.parseDouble(rebate) ;
}
@Override
public double acceptCash(double money) {
return this.moneyRebate * money;
}
}
package com.strategy;
/**
* 返利收費 ,滿多少返多少
* @author Administrator
*
*/
public class CashReturn implements CashSuper {
private double moneyCondition;
private double moneyReturn;
public CashReturn (String moneyCondition ,String moneyReturn){
this.moneyCondition = Double.parseDouble(moneyCondition);
this.moneyReturn = Double.parseDouble(moneyReturn);
}
@Override
public double acceptCash(double money) {
double result = 0 ;
if (money >= this.moneyCondition){
result = money - Math.floor(money/this.moneyCondition) * this.moneyReturn;
}
return result;
}
}
package com.strategy;
/**
* 策略 類
* @author Administrator
*
*/
public class ContentStrategy {
private CashSuper cashSuper;
//初始化,傳入具體策略物件
public ContentStrategy (String type){
if ("normal".equalsIgnoreCase(type)) {
this.cashSuper = new CashNormal();
}
else if ("rebate".equalsIgnoreCase(type)){
this.cashSuper = new CashRebate("0.8");
}
else if ("return".equalsIgnoreCase(type)){
this.cashSuper = new CashReturn("300", "100");
}
}
//呼叫演算法方法
public double getResult (double money){
return cashSuper.acceptCash(money);
}
}
package com.strategy;
/**
* 策略模式是一種定義一系列演算法的方法,從概念上來看,所有的這些演算法都完成相同的工作
* 只是實現不一樣,它可以以相同的方式呼叫所有的演算法,減少了各種演算法類與使用演算法類之間
* 的耦合,只要在分析過程中聽到需要在不同時間應用不同的業務規則,就可以考慮使用策略模式
* 處理這種變化的可能性。
* @author Administrator
*
*/
public class MainRun {
public static void main(String[] args) {
ContentStrategy strategy = new ContentStrategy("rebate");
double returnVal = strategy.getResult(100);
System.out.println("reuturnVal = "+returnVal);
}
}