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); } }