我们通过使用工厂模式,实现了表现层——业务层以及业务层——持久层的解耦
1. 配置文件
2.创建beanFactory
package com.jiangzongqi.bean;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
/**
* @Description:
* @CreateDate: Created in 2019/6/13 09:58
* @Author: jiangzq
*/
public class BeanFactory {
//存放对象
private static Map<String, Object> beans;
//读取配置文件
private static ResourceBundle rb;
static {
rb = ResourceBundle.getBundle("bean");
Enumeration<String> keys = rb.getKeys();
//实例化容器
beans = new HashMap<String, Object>();
while (keys.hasMoreElements()) {
//获取每一个key
String key = keys.nextElement();
//拿到配置文件中的value
String value = rb.getString(key);
//反射
try {
Object o = Class.forName(value).newInstance();
beans.put(key, o);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static Object getBean(String key) {
return beans.get(key);
}
}
3.创建dao及实现类
package com.jiangzongqi.dao;
public interface IAccountDao {
/**
* 模拟保存账户
*/
void saveAccount();
}
package com.jiangzongqi.dao.impl;
import com.jiangzongqi.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
4.创建service及实现类
package com.jiangzongqi.service;
public interface IAccountService {
/**
* 模拟保存账户
*/
void saveAccount();
}
package com.jiangzongqi.service.impl;
import com.jiangzongqi.bean.BeanFactory;
import com.jiangzongqi.dao.IAccountDao;
import com.jiangzongqi.service.IAccountService;
public class AccountServiceImpl implements IAccountService {
IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
public void saveAccount() {
accountDao.saveAccount();
}
}
5. 创建测试类
package com.jiangzongqi.controller;
import com.jiangzongqi.bean.BeanFactory;
import com.jiangzongqi.service.IAccountService;
public class Client {
static IAccountService iAccountService = (IAccountService) BeanFactory.getBean("iAccountService");
public static void main(String[] args) {
iAccountService.saveAccount();
}
}