Java反射的工厂模式应用
2013-01-24 22:41
369 查看
晚上正好讲到Java反射的用法,记录一下Java反射在工厂模式下的应用。
1、普通工厂模式
2、加入反射的工厂模式
3、利用反射+配置文件
第2种方法仍然可以改进,就是利用配置文件指定要实例的类,这样当更改fruit对象的时候就不用重新编译程序,具体代码……木有做。
1、普通工厂模式
package com.djn.helloreflect; public class Hello_0 { public static void main(String[] a){ IFruit f=FruitFactory_0.getInstance("Orange_0"); f.eat(); } }
package com.djn.helloreflect; /** * 总结 * 如果我们需要添加其他的实例的时候只需要 * 1、在后面增加实现; * 2、修改工厂类,增加else if语句 * */ public class FruitFactory_0 { public static IFruit getInstance(String fruitName) { IFruit f = null; if (fruitName.equals("Apple_0")) { f = new Apple_0(); } else if (fruitName.equals("Orange_0")) { f = new Orange_0(); } return f; } } class Apple_0 implements IFruit { public void eat() { System.out.println("Apple_0"); } } class Orange_0 implements IFruit { public void eat() { System.out.println("Orange_0"); } }
2、加入反射的工厂模式
package com.djn.helloreflect; /** * 总结 * 1、需要传入完整的包名和类名,太长了; * */ public class HelloReflect_1 { public static void main(String[] a) { IFruit f = FruitFactory_1.getInstance("com.djn.helloreflect.Apple_1"); if (f != null) { f.eat(); } } } </code></pre> <pre><code> package com.djn.helloreflect; /** * 总结 * 如果我们需要添加其他的实例的时候只需要 * 1、在后面增加实现; * 2、不需要修改工厂类 * */ public class FruitFactory_1 { public static IFruit getInstance(String ClassName) { IFruit f = null; try { f = (IFruit) Class.forName(ClassName).newInstance(); } catch (Exception e) { e.printStackTrace(); } return f; } } class Apple_1 implements IFruit { public void eat() { System.out.println("Apple_1"); } } class Orange_1 implements IFruit { public void eat() { System.out.println("Orange_1"); } }
3、利用反射+配置文件
第2种方法仍然可以改进,就是利用配置文件指定要实例的类,这样当更改fruit对象的时候就不用重新编译程序,具体代码……木有做。
相关文章推荐
- 【Java高级】反射+工厂模式+属性文件的实例应用
- Java基础---基础加强---增强for循环、自动拆装箱及享元、枚举的作用、实现带有构造方法、透彻分析反射的基础_Class类、成员变量的反射、数组参数的成员方法进行反射、数组的反射应用
- 【JAVA - 基础】之反射的原理与应用
- 《Spring 3.x 企业应用开发实战》学习笔记 第三章 IoC容器概述 3.2 相关Java基础知识 类装载器 反射机制
- [零基础学JAVA]Java SE应用部分-36.反射机制与工厂设计模式 推荐
- Java高新技术2----反射应用1
- java反射应用场合
- Java反射在实际工作中的应用笔记
- 反射在Java Swing中的应用
- java反射应用--调用方法与访问属性
- java 反射的应用(将一个java对象转换成一个xml文件)
- java反射的应用 构造方法 成员变量
- java中的反射机制在android中的应用
- Java 反射在实际开发中的应用
- Java 编程的动态性,第3部分: 应用反射
- Java 面试题之反射的应用(如何在List<String> list = new ArrayList<String>();中放入Integer类型的数据)
- JAVA的泛型与反射的联合应用
- Java中的反射的应用
- Java反射的应用
- java反射基础知识(四)反射应用实践