静态工厂解析两种配置文件

原由:代码之间的耦合度过高不利于维护,且修改源代码违背了违背了软件开发领域的“开闭”原则,因此使用配置文件彻底解决耦合性的问题。

下面提供解析两种配置文件的静态工厂

1、使用SAXReader类解析.xml配置文件

public class BeanFactory {

	private static Map<String, Object> map = new HashMap<String, Object>();

	static {
		// 获取SAXReader对象
		SAXReader saxReader = new SAXReader();
		try {
			// 获取XML文件
			Document document = saxReader.read(BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml"));
			// 获取xml文件根元素
			Element rootElement = document.getRootElement();
			// 获取指定元素值
			String id = rootElement.attributeValue("id");
			// 获取类的全路径名
			String clazz = rootElement.attributeValue("class");
			// 通过反射生成对象
			Object obj = Class.forName(clazz).newInstance();
			// 存入集合中
			map.put(id, obj);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 获取对象
	public static Object getBean(String id) {
		return map.get(id);
	}
}

2、使用ResourceBundle类解析.properties配置文件

public class Factory {

	/**
	 * <T>:声明当前方法是一个泛型方法
	 *  返回值T:当前返回值的类型是T类型,T类型到底是什么,运行的时候确定 (T):强制类型转换
	 * @param inter
	 * @return
	 */
	public static <T> T getBean(String inter) {

		// inter:接口名称,创建实现类
		// 读取配置文件,获取对应关系
		ResourceBundle bundle = ResourceBundle.getBundle("bean");
		// 根据指定的key获取对应全路径类名
		String className = bundle.getString(inter);
		try {
			// 获取class类对象
			Class clazz = Class.forName(className);
			// 反射生成指定对象,并返回
			return (T) clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}


猜你喜欢

转载自blog.csdn.net/jinYwuM/article/details/80496047