在sping的IOC之前看到使用工厂模式动态创建对象,感觉有些思想在里面,当做笔记记录下来。
配置文件:bean.properties
accountService=com.wcgxy.service.impl.AccountServiceImpl
accountDao=com.wcgxy.dao.impl.AccountDaoImpl
对应的就是两个接口的普通实现类
重点就是这个BeanFactory 工厂类
public class BeanFactory{
//定义一个Properties对象
private static Properties props;
//定义一个Map,用于存放我们要创建的对象。(容器)
private static Map<String,Object> beans; //通过一个字符串就可以找到一个对象
//使用静态代码块为Properties和beans赋值
static{
try{
//实例化对象
props = Properties.class.newInstance();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String,Object>();
//取出配置文件中所有的Key
Enumeration keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()){
//取出每个Key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key,value);
}
}catch(Exception e){
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据bean的名称获取对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);//通过传入的字符串就可以直接从集合里面取出对象
}
}
最后写一个测试类,循环调用getBean,打印发现对象是单列的。到此通过工厂模式动态创建对象的方式就接结束了。