本文基于下述教程编写:【B站】ssm教程
工厂模式解耦思想
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200720221959743.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0plbGx5X0JlYW4=,size_16,color_FFFFFF,t_70)
简单应用,实现业务层和持久层解耦:
public class BeanFactory {
//加载配置文件操作类
private static Properties props = null;
//存放已经生成好的实例对象的容器
private static Map<String, Object> beans = null;
static {
try {
System.out.println("工厂里面执行静态代码块......");
props = new Properties();
//使用类加载器获取配置文件,得到流
InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
//Properties加载流
props.load(inputStream);
beans = new HashMap<String, Object>();
//返回properties文件字段名内容
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();
//存入容器
beans.put(key, value);
}
} catch(Exception e){
e.printStackTrace();
}
}
/**
* 根据Bean的名称获取Bean对象
*/
public static Object getBean(String beanName) {
//多例工厂模式,未能实现全局单类对象的需求
/*Object bean = null;
try {
//得到配置文件下对应Bean的包路径
String beanPath = props.getProperty(beanName);
//反射创建对象
bean = Class.forName(beanPath).newInstance();
} catch (Exception e) {
e.printStackTrace();
}*/
return beans.get(beanName);
}
}
/**
* 模拟表现层,用于调用业务层
*/
public class Client {