使用配置文件+反射机制+工厂模式模拟IOC解耦(单例)案例
(1)客户端:
package com.njau.UI;
import com.njau.Util.BeanFactory;
import com.njau.service.AccountService;
public class Client {
public static void main(String[] args) {
//AccountService accountService = new AccountServiceImpl();
AccountService accountService = (AccountService)BeanFactory.getBean("accountService");
accountService.saveData();
}
}
(2)service接口
package com.njau.service;
public interface AccountService {
//模拟保存数据
void saveData();
}
service接口实现类
package com.njau.service.serviceImpl;
import com.njau.Util.BeanFactory;
import com.njau.dao.AccountDao;
import com.njau.dao.daoimpl.AccountDaoImpl;
import com.njau.service.AccountService;
public class AccountServiceImpl implements AccountService {
//private AccountDao accountDao = new AccountDaoImpl();
private AccountDao accountDao = (AccountDao)BeanFactory.getBean("accountDao");
@Override
public void saveData() {
accountDao.saveData();
}
}
(3)dao接口
package com.njau.dao;
public interface AccountDao {
//模拟保存数据
void saveData();
}
dao接口实现类
package com.njau.dao.daoimpl;
import com.njau.dao.AccountDao;
public class AccountDaoImpl implements AccountDao {
@Override
public void saveData() {
System.out.println("保存成功!!");
}
}
(4)配置文件解析(含反射机制与工厂模式)
package com.njau.Util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class BeanFactory {
//定义一个Properties对象
private static Properties properties;
//定义一个Map,用于存放我们要创建的对象,我们把它称之为容器
private static Map<String,Object> beans;
//使用静态代码块为Properties对象赋值
static {
//实例化对象
properties = new Properties();
//获取properties对象的流对象
InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
try {
properties.load(inputStream);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration<Object> keys = properties.keys();
//遍历枚举
while (keys.hasMoreElements()){
//从枚举中取出所有的key
String key = keys.nextElement().toString();
System.out.println(key);
//通过key,取出配置文件中对应的值,即全限定类名
String beanPath = properties.getProperty(key);
//通过全限定类名用反射的方式创建实例
Object instance = Class.forName(beanPath).newInstance();
//将key和实例存入map集合中,即存入beans中
beans.put(key,instance);
}
} catch (IOException e) {
e.printStackTrace();
//初始化异常
throw new ExceptionInInitializerError("读取bean配置文件出错");
} catch (Exception e) {
e.printStackTrace();
System.out.println("在遍历keys时,可能出现了异常");
}
}
/**
* 通过beanName获取对象(单例)
* @param beanName
* @return
*/
public static Object getBean(String beanName){
Object bean = beans.get(beanName);
return bean;
}
}
(5)配置文件
accountService=com.njau.service.serviceImpl.AccountServiceImpl
accountDao=com.njau.dao.daoimpl.AccountDaoImpl
参考:
https://blog.csdn.net/weixin_44268792/article/details/99207563
表示感谢!!