回顾
上一篇文章策略稍微封装了一下,策略的使用并没有完全面向接口编程,它把所有的策略类都暴露出去了。如果用户要使用策略,她还得new一下策略类。想到new,创建模式就得派上用场,如工厂方法模式、建造者模式等。由于我们需要的策略类并没有那么复杂,故采用工厂方法模式。工厂方法模式,通过类的全限定名利用反射获取类的实例。那么类的全限定名该怎么维护呢?可以通过读取配置的方式,还可以枚举,完成映射,实现策略类的隐藏。然后用工厂方法模式根据映射创建策略对象。
类图设计
策略枚举
/**
* Created by CeaM on 2021/1/22 0022 21:55
* 策略枚举
*/
public enum StrategyMan {
SteadyDeduction("com.ceam.designer.strategy.blend.SteadyDeduction"),
FreeDeduction("com.ceam.designer.strategy.blend.FreeDeduction");
String value = "";
private StrategyMan(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
策略工厂
/**
* Created by CeaM on 2021/1/22 0022 21:31
* 这里的工厂到时候换成SpringApplicationContextFactory
*/
public class StrategyFactory {
//
public static IDeduction getDeduction(StrategyMan strategy){
IDeduction deduction = null;
try {
deduction = (IDeduction) Class.forName(strategy.getValue()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return deduction;
}
}