策略模式(Strategy),定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法的变化可独立于使用它的客户。
package gof23;
public class StrategyTest {
public static void main(String[] args) {
CashContext cc = null;
cc = new CashContext("正常收费");
System.out.println("收费为:" + cc.getResult(2000) +"元");
cc = new CashContext("满300返100");
System.out.println("收费为:" + cc.getResult(2000) +"元");
cc = new CashContext("打8折");
System.out.println("收费为:" + cc.getResult(2000) +"元");
}
}
class CashContext {
private CashSuper cs = null;
public CashContext(String type) {
switch(type) {
case "正常收费":
CashNormal cs0 = new CashNormal();
cs = cs0;
break;
case "满300返100":
CashReturn cs1 = new CashReturn(300, 100);
cs= cs1;
break;
case "打8折":
CashRebate cs2 = new CashRebate(0.8);
cs = cs2;
break;
}
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
abstract class CashSuper {
public abstract double acceptCash(double money);
}
/*
* 正常收费,原价返回
*/
class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
/*
* 打折收费,初始化时,需要输入折扣率,如0.8
*/
class CashRebate extends CashSuper {
private double moneyRebate = 1d;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
/*
* 返利收费,初始化时必须输入返利条件和返利值,比如满300返100,
* 则moneyCondition为300,moneyReturn为100
*/
class CashReturn extends CashSuper {
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn(double moneyCondition, double moneyReturn) {
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
double result = money;
if(result > moneyCondition)
result = money - Math.floor(money / moneyCondition) * moneyReturn;
return result;
}
}
运行结果为:
收费为:2000.0元
收费为:1400.0元
收费为:1600.0元