策略模式
场景:商场收银软件,营业员根据客户购买的商品的数量和单价,向客户收费。
使用简单工厂模式
//收费抽象类
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
//正常收费类
public class CashNormal extends CashSuper{
public double acceptCash(double money) {
// TODO Auto-generated method stub
return money;
}
}
//打折收费类
public class CashRebate extends CashSuper {
private double moneyRebate = 1;
public CashRebate(double moneyRebate) {
// TODO Auto-generated constructor stub
this.moneyRebate = moneyRebate;
}
public double acceptCash(double money) {
// TODO Auto-generated method stub
return money*moneyRebate;
}
}
//返利收费子类
public class CashReturn extends CashSuper{
private double moneyCondition = 0;
private double moneyReturn = 0;
private DecimalFormat df= new DecimalFormat("0.00");
public CashReturn(double moneyCondition,double moneyReturn) {
// TODO Auto-generated constructor stub
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
public double acceptCash(double money) {
// TODO Auto-generated method stub
if(money>moneyCondition) {
money = money-Double.parseDouble(df.format(money/moneyCondition))*moneyReturn;
}
return money;
}
}
//工厂
public class CashFactory {
public static CashSuper createCashAccept(String type) {
CashSuper cs = null;
switch(type){
case "正常收费":
cs = new CashNormal();
break;
case "打八折":
cs = new CashRebate(0.8);
break;
case "满300返100":
cs = new CashReturn(300, 100);
break;
}
return cs;
}
}
策略模式+工厂模式
//策略类
public class CashContext {
private CashSuper cs = null;
public CashContext(String type) {
switch(type) {
case "打八折":
cs = new CashRebate(0.8);
break;
case "原价":
cs = new CashNormal();
break;
case "满300返100":
cs = new CashReturn(300,100);
break;
}
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
具体调用
public class CashTest {
public static void main(String[] args) {
//假定商品单价和数量
double num = 3;
double price = 4;
double total = 0;
//1.工厂模式调用
CashSuper cs = CashFactory.createCashAccept("打八折");
total = cs.acceptCash(num*price);
//2.策略模式+工厂模式
CashContext cc = new CashContext("打八折");
total = cc.getResult(num*price);
}
}
从具体的调用分析,工厂模式只是解决了类的创建,这些不同情况下创建的子类实际是具有共同目的的不同算法的实现,而这些具体的实现与调用者无关,因此,策略类和工厂的区别在于策略类即实现了工厂模式下的具体子类的创建还封装了具体的算法,使得客户端仅需要“认识”策略类对象,降低了耦合。
ps:实际书中的内容更加循序渐进的介绍了工厂模式、策略模式、和工厂+策略模式的实现,实际单纯的策略模式就会将子类的创建的这一步骤放到客户端(调用者),因此省略了单独的策略模式的介绍。
最后还是附上很厉害的模式详解链接,各个模式的优缺点都说的特别清楚,感谢!
https://github.com/WiKi123/DesignPattern/blob/master/DesignPatternIntroduce.md