工厂模式与反射
2015-08-09 22:16
127 查看
定义一个接口以及两个实现了该接口的类:
[code]package Reflect; interface fruit{ public void eat(); } class Apple implements fruit{ public void eat(){ System.out.println("Apple Eat"); } } class Orange implements fruit{ public void eat(){ System.out.println("Orange Eat"); } }
未使用反射的工程模式
[code]//构造工厂类 //也就是说以后我们在添加其他的实例的时候只需要修改工厂类即可 class Factory{ public static fruit getInstance(String fruitName){ fruit f = null; if("Apple".equals(fruitName)){ f = new Apple(); } if("Orange".equals(fruitName)){ f = new Orange(); } return f; } } class Hello{ public static void main(String[] a){ fruit f = factory.getInstance("Apple"); f.eat(); } }
弊端:当我们添加一个实现接口的类的时候,就需要修改工厂类。如果我们添加的实现类很多,修改的工厂类的地方也会很多。
使用反射机制的工厂类
[code]class Factory{ public static fruit getInstance(String ClassName){ fruit f = null; try{ f=(fruit)Class.forName(ClassName).newInstance(); }catch (Exception e){ e.printStackTrace(); } return f; } } class Hello { public static void main(String[] a){ fruit f = factory.getInstance("Reflect.Apple"); if(f!=null) f.eat(); } }
好处:即使我们添加任意多的实现接口的子类的时候,工厂类也不需要修改。
弊端:需要传入完整的包和类名,而且用户无法知道一个接口有多少可以使用的子类。
使用配置文件的工厂模式
创建一个fruit.properties的资源文件,内容为:apple=Reflect.Apple
orange=Reflect.Orange
主类的代码如下:
首先是操作property文件的类:
[code]//操作属性文件类 class Init{ public static Properties getProperties() throws FileNotFoundException,IOException{ Properties pro = new Properties(); File f = new File("fruit.properties"); if(f.exists()){ pro.load(new FileInputStream(f)); }else { pro.setProperty("apple","Reflect.Apple"); pro.setProperty("orange","Reflect.Orange"); pro.store(new FileOutputStream(f),"FRUIT CLASS"); } return pro; } }
Factory工厂类与Hello驱动类:
[code]class Factory{ public static fruit getInstance(String ClassName){ fruit f = null; try{ f=(fruit)Class.forName(ClassName).newInstance(); }catch (Exception e){ e.printStackTrace(); } return f; } } class Hello { public static void main(String[] args)throws FileNotFoundException,IOException{ Properties pro = Init.getProperties(); fruit f = factory.getInstance(pro.getProperty("apple")); if(f!=null) f.eat(); } }
好处:可以直接在文件中修改对应关系。
参考资料:
java反射详解
相关文章推荐
- HDU 4521-小明序列(线段树好题)
- Socket 中的send函数和recv函数
- CSP 直方图中的最大矩形
- SSH整合环境下web应用自带web.xml文件的配置
- 事务(JDBC、Hibernate、Spring)
- 模仿块级作用域
- (番外)使用DFS和BFS实现拓扑排序
- (大数据工程师学习路径)第一步 Linux 基础入门----Linux 下软件安装
- VS 2013的初配置
- Caffe学习:Layers
- 畅通工程
- 从优化到再优化,最长公共子串
- LeetCode(147) Insertion Sort List
- 搜索论文网址
- 简单封装的httpclient4请求类
- 搜索 剪枝
- 微信公众号抢现金红包活动的核心代码分析(asp.net C#)
- Struts2实现文件的上传与下载
- 关于VMware 11 虚拟机不能通过DCHP获取到地址的解决办法
- 一个操盘手的自白:做盘的奥秘