工厂模式是我们最常用的实例化对象的模式,使用工厂方法代替了new操作的一种模式。
从xml文件获取相应的实例的信息,获得带实例的代码:
package com.designmode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* Description:
* 实现一个工厂模式
*
* @author lee
* */
public class FactoryMode {
/**
* Description:
* 主方法
*
* */
public static void main(String[] args){
//通过getInstance()方法获取Person对象
Person p = (Person)getInstance();
System.out.println(p);
}
/**
* Description:
* 通过dom4j解析xml文件,获取对象信息。将其封装在一个对象内,返回。
* (关于运用dom4j解析xml文件,可以查看我的另外一篇博客)
*
* @return
* */
public static Object getInstance(){
int id = 0;
String name = "";
String className = "";
Object o = null;
//xml解析器
SAXReader sax = new SAXReader();
try{
//获取一个文档实例
Document doc = sax.read(new FileInputStream("./people.xml"));
//获取根元素,即是<person></person>
Element element = doc.getRootElement();
//获取id和name的值,和Person类的全称
id = Integer.parseInt(element.elementText("id"));
name = element.elementText("name");
className = element.elementText("class");
}catch(IOException | DocumentException e){
e.printStackTrace();
}
try{
//通过Person类全称反射获取Class对象
Class<?> clazz = Class.forName(className);
//通过Class对象获取Constructor对象
Constructor<?> constructor = clazz.getConstructor();
//同过Contructor对象获取相应的实例
o = constructor.newInstance();
//通过Class对象获取Field对象,并设置其值
Field Id = clazz.getField("id");
Id.set(o, id);
Field Name = clazz.getField("name");
Name.set(o, name);
}catch(Exception e){
e.printStackTrace();
}
return o;
}
}
/**
* Description:
* 实现一个人类
*
* @author lee
* */
class Person{
public int id;
public String name;
/**
* Description:
* 默认构造方法
*
* */
public Person(){}
/**
* Description:
* 初始化id和name的构造方法
*
* @param id id
* @param name 名字
* */
public Person(int id, String name){
this.id=id;
this.name=name;
}
/**
* Description:
* 重写toString方法
*
* @return "id = "+id+", name = "+name
* */
@Override
public String toString(){
return "id = "+this.id+", name = "+this.name;
}
//get和set方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
people.xml的代码:
<person>
<class>com.designmode.Person</class>
<id>1</id>
<name>wang</name>
</person>