一、简单工厂实现
现金收费抽象类:
package ch02strategy;
abstract class CashSuper {
public abstract double acceptCash(double money);
}
正常收费子类:
package ch02strategy;
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
// TODO Auto-generated method stub
return money;
}
}
打折收费子类:
package ch02strategy;
public class CashRebate extends CashSuper {
private double moneyRebate = 1d;
public CashRebate(String moneyRebate){
this.moneyRebate = Double.parseDouble(moneyRebate);
}
@Override
public double acceptCash(double money) {
// TODO Auto-generated method stub
return money * moneyRebate;
}
}
返利收费子类:
package ch02strategy;
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) {
// TODO Auto-generated method stub
double result = money;
if (money >= moneyCondition) {
result = money - Math.floor(money / moneyCondition) * moneyReturn;
}
return result;
}
}
现金收费工厂类:
package ch02strategy;
public class CashFactory {
public static CashSuper createCashAccept(String type){
CashSuper cs = null;
char charType = type.charAt(0);
//char charType = (char)type;
switch (charType){
case 'n':
cs = new CashNormal();
break;
case 'r':
CashReturn cr1 = new CashReturn("300","100");
cs = cr1;
break;
case '8':
CashRebate cr2 = new CashRebate("0.8");
cs = cr2;
break;
}
return cs;
}
}
二、策略模式
策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户(客户端)。
class Context {
Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void ContextInterface() {
strategy.AlgorithmInterface();
}
}
策略与简单工厂结合:
package ch02strategy;
public class CashContext {
CashSuper cs = null;
public CashContext(String type){
char charType = type.charAt(0);
//char charType = (char)type;
switch (charType){
case 'n':
cs = new CashNormal();
break;
case 'r':
CashReturn cr1 = new CashReturn("300","100");
cs = cr1;
break;
case '8':
CashRebate cr2 = new CashRebate("0.8");
cs = cr2;
break;
}
}
public double getResult(double money){
return cs.acceptCash(money);
}
}
三、策略模式解析
switch语句看着总是让人不爽啊。。。