今天又学习了一种模式,策略模式。总体感觉策略模式与简单工厂模式很像,简单工厂模式通过一个工厂类来创建具体产品角色,策略模式则通过上下文类来创建具体算法类。下面是一个以超市正常收费,打折,返利为场景的实例,将策略模式与简单工厂模式结合起来的一个例子。
(1)首先创建一个现金收费抽象类
/**
* 现金收费抽象类
* */
public abstract class CashSuper {
abstract double acceptCash(double money);
}
(2)然后创建相应的算法实现类,如正常收费,打折,返利
/**
* 正常收费子类
* */
public class CashNormal extends CashSuper{
@Override
double acceptCash(double money) {
return money;
}
}
/**
* 打折收费子类
* */
public class CashRebate extends CashSuper{
private double moneyDiscount;
public CashRebate(double moneyDiscount) {
this.moneyDiscount=moneyDiscount;
}
@Override
double acceptCash(double money) {
return moneyDiscount*money;
}
}
/**
* 返利收费子类
* */
public class CashReturrn extends CashSuper{
private double moneyCondition;
private double moneyReturn;
public double getMoneyCondition() {
return moneyCondition;
}
public void setMoneyCondition(double moneyCondition) {
this.moneyCondition = moneyCondition;
}
public double getMoneyReturn() {
return moneyReturn;
}
public void setMoneyReturn(double moneyReturn) {
this.moneyReturn = moneyReturn;
}
public CashReturrn(double moneyCondition,double moneyReturn) {
this.moneyCondition=moneyCondition;
this.moneyReturn=moneyReturn;
}
@Override
double acceptCash(double money) {
return money-Math.floor(money/moneyCondition)*moneyReturn;
}
}
(3)创建策略类
/**
* 策略类
* */
public class StrategyContext {
private CashSuper cashSuper;
public StrategyContext(int type){
switch (type) {
case Constants.NORMAL_TYPE:
cashSuper=new CashNormal();
break;
case Constants.DISCOUNT_TYPE:
cashSuper=new CashRebate(0.8);
break;
case Constants.RETURN_TYPE:
cashSuper=new CashReturrn(500,100);
break;
}
}
public double getResult(double money) {
return cashSuper.acceptCash(money);
}
}
(4)测试类
public class Test {
public static void main(String[] args) {
StrategyContext context=new StrategyContext(Constants.RETURN_TYPE);
double actualMoney=context.getResult(600);
System.out.println(actualMoney);
}
}
输出:
500.0