用JAVA设计模式设计:使用反射机制来实现工厂类并使用XML作为工厂类的配置文件格式
在Java程序设计中,可以使用反射机制来实现工厂模式,并使用XML作为工厂类的配置文件格式,具体实现如下:
- 创建一个抽象工厂类,定义一个用于创建对象的抽象方法。
public abstract class AbstractFactory<T> {
public abstract T createObject(String type);
}
2.创建一个具体工厂类,继承自抽象工厂类,实现createObject方法,并使用反射机制动态创建对象。
public class ConcreteFactory extends AbstractFactory<Object> {
@Override
public Object createObject(String type) {
Object object = null;
try {
Class<?> cls = Class.forName(type);
object = cls.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
return object;
}
}
3.创建一个XML配置文件,定义需要创建的对象类型及其对应的类名,如下所示:
<config>
<type name="TypeA">com.example.TypeA</type>
<type name="TypeB">com.example.TypeB</type>
</config>
4.创建一个工厂类配置文件解析器,用于读取XML配置文件并生成具体工厂类的对象。
public class FactoryConfigParser {
public static AbstractFactory<Object> parse(String configPath) {
AbstractFactory<Object> factory = new ConcreteFactory();
try {
DocumentBuilderFactory factoryBuilder = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factoryBuilder.newDocumentBuilder();
Document document = builder.parse(configPath);
Element root = document.getDocumentElement();
NodeList typeNodes = root.getElementsByTagName("type");
for (int i = 0; i < typeNodes.getLength(); i++) {
Element type = (Element) typeNodes.item(i);
String name = type.getAttribute("name");
String className = type.getTextContent();
factory.register(name, className);
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return factory;
}
}
5.在客户端程序中使用工厂类来创建对象。
public static void main(String[] args) {
AbstractFactory<Object> factory = FactoryConfigParser.parse("config.xml");
Object objA = factory.createObject("TypeA");
Object objB = factory.createObject("TypeB");
}