您的位置:首页 > 编程语言 > Java开发

Java反射的工厂模式应用

2013-01-24 22:41 369 查看
晚上正好讲到Java反射的用法,记录一下Java反射在工厂模式下的应用。

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对象的时候就不用重新编译程序,具体代码……木有做。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: