关于简单工厂设计模式的讲解,可参考博文《设计模式: 简单工厂模式》,此处不再介绍; 我们先观察之前介绍的关于简单工厂:
public class OperateFactory { public static Operation createOperate(char operate) { Operation oper = null; switch (operate) { case '+': oper = new OperationAdd(); break; case '-': oper = new OperationSub(); break; case '*': oper = new OperationMul(); break; case '/': oper = new OperationDiv(); break; default: break; } return oper; } }
可以发现, 如果我们一旦新增加一个运算方法,则必须要修改工厂类。 如果此时希望在扩充子类时不用修改工厂类,则必须使用反射完成。
public class OperateProxyFactory { public static Operation createOperate(String operate) { Operation oper = null; try { oper = (Operation) Class.forName(operate).newInstance(); } catch (Exception e) { e.printStackTrace(); } return oper; } }
使用该反射工厂类,我们就必须在创建实例时,传入包.类全名称:
public class FactoryDemo { public static void main(String[] args) { Operation operator = OperateProxyFactory .createOperate("com.chen.yuan.factory1.OperationAdd"); operator.setNumA(10); operator.setNumB(20); operator.getResult(); } }
以上,我们发现,确实不用再修改工厂类了,但是程序在使用时候,传入完整的"包.类",肯定麻烦,所以,我们通过配置文件的方式来保存这些完整的类路径。
那我们来搞个结合属性文件的工厂模式:
先创建属性文件operation.propertie
add= com.chen.yuan.factory1.OperationAdd div= com.chen.yuan.factory1.OperationDiv mul= com.chen.yuan.factory1.OperationAdMul sub= com.chen.yuan.factory1.OperationSub
然后实现客户端类:
public class FactoryDemo { public static void main(String[] args) { Properties pro = Init.getPro(); String add = pro.getProperty("add"); Operation operator = OperateProxyFactory .createOperate(add); operator.setNumA(10); operator.setNumB(20); operator.getResult(); } } class Init { public static Properties getPro() { Properties pro = new Properties(); try { pro.load(new FileInputStream("operation.properties")); } catch (Exception e) { e.printStackTrace(); } return pro; } }
通过这种方法,配置起来反射所需要的包.类全路径就更加方便啦~~~~