IOC降低程序的耦合问题
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。
一、原始方法需要设置beanfactory
测试类
/**
* 模拟表现层,用于调用业务层
*/
public class Client {
public static void main(String[] args) {
/*IAccountService accountService = new AccountServiceImpl();*/
for (int i = 0; i < 5; i++) {
IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
System.out.println(as);
as.saveAccount();
}
}
}
BeanFactory工厂类
public class BeanFactory {
//定义一个Properties
private static final Properties properties;
//定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
private static final Map<String, Object> beans;
//使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
properties = new Properties();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的Key
Enumeration keys = properties.keys();
//遍历枚举
while (keys.hasMoreElements()) {
//取出每个key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = properties.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器之中
beans.put(key, value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据Bean的名称获取bean对象
*
* @return
*/
public static Object getBean(String beanName) {
return beans.get(beanName);
}
bean.properties
总结:
-
不使用IAccountService accountService = new AccountServiceImpl()直接实例化一个需要的服务对象 而是通过一个工厂去生产,降低了耦合性 只能是降低,不可能去除,如果类与类没有一点耦合,那么必定有多余的,所以耦合是存在的
