承接上一次:工厂模式解耦-基本版:https://blog.csdn.net/weixin_56697114/article/details/116375983
package ouhe;
//表现层
public class Client {
public static void main(String[] args) throws ClassNotFoundException {
//IAccountService as = new AccountServiceImpl();
for(int i=0; i<5; i++) {
IAccountService as = (IAccountService) BeanFactory.getBean("AccountService");
System.out.println("main线程:"+as);
}
}
}
结果:
问题:这样每次都会创建新的对象,原因如下图,没必要创建多例对象,这里使用单例对象可以节省更多的资源。
clazz = Class.forName(s).newInstance();
最终版:
package ouhe;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
//创建Bean对象的工厂
public class BeanFactory {
/*
* 只能用于读取properties文件
* 只能读取,不能写入
* 只能读取类路径下的文件
* */
private static ResourceBundle rb = ResourceBundle.getBundle("bean");
//定义一个容器存放所以的bean对象
private static Map<String, Object> map = new HashMap<>();
static {
try {
//1、获取所以的key
Enumeration<String> keys = rb.getKeys();
//2、遍历所以key
while(keys.hasMoreElements()) {
//取出key
String key = keys.nextElement();
//获取value
String bean = rb.getString(key);
//反射获取bean对象
Object value = Class.forName(bean).newInstance();
map.put(key, value);
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static Object getBean(String beanName) {
return map.get(beanName);
}
}
这样的结果为: