首页 > 代码库 > 设计模式之策略模式
设计模式之策略模式
有一天,杨哥没事晃悠到了一家商场,发现商场正在搞活动,有些商品打8折,有些满100还返1元等等,这时杨哥就在想,每当到了商场活动,收费系统该如何来应对不同的打折方式的呢,于是在回来的路上左思右想,回到家杨哥动手使用策略模式模拟写了一个收费系统程序,废话不多说,直接先上个图:
再上代码:
收费抽象类CashSuper:
package cel_designmode;
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
正常收费策略类CashNormal:
package cel_designmode;
public class CashNormal extends CashSuper{
@Override
public double acceptCash(double money) {
return money;
}
}
满300返100收费策略类CashReturn:
package cel_designmode;
public class CashReturn extends CashSuper{
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn(String moneyCondition,String moneyReturn)
{
this.moneyCondition = Double.parseDouble(moneyCondition);
this.moneyReturn = Double.parseDouble(moneyReturn);
}
@Override
public double acceptCash(double money) {
double result = money;
if (money >= moneyCondition)
result=money- Math.floor(money / moneyCondition) * moneyReturn;
return result;
}
}
打8折收费策略类CashRebate:
package cel_designmode;
public class CashRebate extends CashSuper{
private double moneyRebate = 1d;
public CashRebate(String moneyRebate)
{
this.moneyRebate = Double.parseDouble(moneyRebate);
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
收费策略CashContext:
package cel_designmode;
//收费策略Context
public class CashContext {
//声明一个现金收费父类对象
private CashSuper cs;
//设置策略行为,参数为具体的现金收费子类(正常,打折或返利)
public CashContext(CashSuper csuper)
{
this.cs = csuper;
}
//得到现金促销计算结果(利用了多态机制,不同的策略行为导致不同的结果)
public double GetResult(double money)
{
return cs.acceptCash(money);
}
}
main函数:
package cel_designmode;
public class StrategyMain {
public static void main(String[] args) {
double total = 0.0d;//用于总计
CashContext cc = null;
String type="正常收费";
switch (type)
{
case "正常收费":
cc = new CashContext(new CashNormal());
break;
case "满300返100":
cc = new CashContext(new CashReturn("300", "100"));
break;
case "打8折":
cc = new CashContext(new CashRebate("0.8"));
break;
}
double totalPrices = 0d;
totalPrices = cc.GetResult(100 * 30);
total = total + totalPrices;
System.out.print(total);
}
}
运行效果:
原理:
策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
设计模式之策略模式