【代码积累】replace constructor with factory method
来源:互联网 发布:mac百度云下载速度慢 编辑:程序博客网 时间:2024/06/03 23:49
import java.lang.reflect.InvocationTargetException;/*典型的遵循OCP原则的编程技巧,结合了继承,反射; * 适用于需要大量创建同一族对象的场合,即,这些对象有共同的父类,但是各自类型不同; * 通常情况下,如果使用子类的构造器构造,需要在create方法中放置一个switch结构,当需要增加子类类型时,不便于扩展; * 使用反射,则只需要根据入参自动创建,创建对象部分的代码可以复用,不需要修改; * 带来的弊端是如果指定类型名称错误,或者类型不存在,则会创建失败,使用replace parameters with methods规避,但会带来维护工作量*/public class Test {public void test() {PersonFactory pFac = new PersonFactory();Person mike = pFac.create("Mike", "Salesman");Person kate = pFac.create("Kate", "Teacher");System.out.println("Mike:name="+mike.getName()+",vocation="+mike.getVocation());System.out.println("Kate:name="+kate.getName()+",vocation="+kate.getVocation());}public class PersonFactory {public Person create(String name,String vocation) {Person person = null;try {/*Class.forName must use the fully qualified name of the class*/person = (Person)(Class.forName(vocation).getDeclaredConstructor(String.class).newInstance(name));} catch (InstantiationException | IllegalAccessException| IllegalArgumentException | InvocationTargetException| NoSuchMethodException | SecurityException| ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return person;}//replace parameters with methodspublic Salesman createSalesman(String name) {return new Salesman(name);}}}
阅读全文
0 0
- 【代码积累】replace constructor with factory method
- 【代码积累】replace constructor with factory
- 简化函数调用之十二 :Replace Constructor with Factory Method(以「工厂函数」取代「构造函数」)
- java 代码细节(Replace Method with Method Object)
- Replace Method with Method Object
- 代码重构(一)-用函数对象代替函数(replace method with method object)
- 02. Factory Method模式代码
- Replace Method with Method Object(以函数对象取代函数)
- 【代码积累】factory pattern without reflection
- CSharp Algorithm - Replace multiplication operator with a method
- Factory Method
- factory method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- 【代码积累】reflection study
- Windows 下 配置 ngrok ngrok使用教程
- ecshop运行超过30秒超时的限制解决办法
- session&servlet
- Android中handler消息处理机制完全解析,带你从源码的角度彻底理解
- 【代码积累】replace constructor with factory method
- GPS定位+经纬度定位
- GIT
- php.ini-development 与 php.ini-production
- Linux scp 使用详解
- JAVA国际化配置
- 【代码积累】replace constructor with factory
- 机器学习|决策树算法与python实现
- requset&response