1. 程序需求
商场收费系统,需要支持正常收费,打折收费,现金返利,积分等计费方式。
2. 简单工厂模式
2.1 UML
2.2 Java实现
Cash
package simple_factory_pattern.market;
public abstract class Cash {
public double originCash; //原价
public abstract double acceptCash();
}
CashNormal
package simple_factory_pattern.market;
public class CashNormal extends Cash {
@Override
public double acceptCash() {
return originCash;
}
}
CashRebate
package simple_factory_pattern.market;
public class CashRebate extends Cash {
private double rebate;
public CashRebate(double rebate) {
this.rebate = rebate;
}
@Override
public double acceptCash() {
return originCash * rebate;
}
}
CashReturn
package simple_factory_pattern.market;
public class CashReturn extends Cash {
private double condition;
private double ret;
public CashReturn(double condition, double ret) {
this.condition = condition;
this.ret = ret;
}
@Override
public double acceptCash() {
if (originCash > condition){
return originCash - (Math.floor(originCash / condition) * ret);
}
return originCash;
}
}
CashAcceptFactory
package simple_factory_pattern.market;
public class CashAcceptFactory {
public static Cash createCash(String select){
Cash cash = null;
switch (select){
case "原价支付":
cash = new CashNormal();
break;
case "打8折":
cash = new CashRebate(0.8);
break;
case "满300减100":
cash = new CashReturn(300, 100);
break;
}
return cash;
}
}
Test
package simple_factory_pattern.market;
public class Test {
public static void main(String[] args) {
Cash cash = CashAcceptFactory.createCash("打8折");
cash.originCash = 500;
System.out.println(cash.acceptCash());
}
}
3. 结合策略模式
简单工厂模式虽然也能解决这个问题, 但这个模式只是解决对象的创建问题, 而且由于工厂本身包括了所有的收费方式, 商场是可能经常性地更改打折额度和返利额度, 每次维护或扩展收费方式都要改动这个工厂, 以致代码需重新编译部署, 这真的是很糟糕的处理方式。我们尝试使用策略模式加简单工厂模式对上述代码进行优化。
增加CashContext
package strategy_pattern.market;
import simple_factory_pattern.market.Cash;
import simple_factory_pattern.market.CashNormal;
import simple_factory_pattern.market.CashRebate;
import simple_factory_pattern.market.CashReturn;
public class CashContext {
private Cash cash = null;
public CashContext(String type, double money) {
switch (type){
case "原价支付":
cash = new CashNormal();
break;
case "打8折":
cash = new CashRebate(0.8);
break;
case "满300减100":
cash = new CashReturn(300, 100);
break;
}
cash.originCash = money;
}
public double acceptCash(){
return cash.acceptCash();
}
}
Test
package strategy_pattern.market;
public class Test {
public static void main(String[] args) {
CashContext cashContext = new CashContext("打8折", 500);
System.out.println(cashContext.acceptCash());
}
}
通过上面的改造,计费算法和客户端完全分离,客户端甚至不需要知道Cash类的存在。
4. 总结
策略模式是一种定义一系列算法的方法, 从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同, 它可以以相同的方式 调用所有的算法,减少了各种算法类与使用算法类之间的耦合。