工厂模式创建了一个生产对象的工厂,是很常用的一种模式。通常可以把工厂模式划分为工厂方法,抽象工厂,反射工厂三种模式。工厂方法和抽象工厂的耦合度较大,所以在C#和Java之类支持反射(Reflection)的语言中,一般选择使用反射工厂。反射工厂在程序运行时通过类装载器动态地装载所需的类,这样,在增加产品实现时,就不必再修改工厂类了,消除了产品类和工厂类之间的耦合。
我们以动物工厂为例:
//先引入动物的接口和实现 Java代码
interface Animal {
public void eat();
}
class Dog implements Animal {
public void eat() {
System.out.println("Dog is eating");
}
}
class Cat implements Animal {
public void eat() {
System.out.println("Cat is eating");
}
}
下面是我们的主角,动物工厂:
//:AnimalFactory.java

/** *//**
* Factory of Design Patterns
* @author http://blog.youkuaiyun.com/nyzhl/
*/
public class AnimalFactory ...{

public static Animal Produce(String className) ...{
Animal production = null;
try ...{
production = (Animal)Class.forName(className);
} catch (ClassNotFoundException e) ...{
e.printStackTrace();
}
return production;
}
}
///~
反射工厂模式详解

本文介绍了工厂模式中的反射工厂实现方式,通过Java代码示例详细解释了如何利用反射机制创建对象,以此降低产品类与工厂类之间的耦合度。
1894

被折叠的 条评论
为什么被折叠?



