程序之间的耦合
- 类之间的依赖
- 方法之间的依赖
类方法介绍
解耦
降低程序之间的依赖关系
程序开发中应做到,编译器不依赖,运行时才依赖
解耦的思想
第一步:使用反射来创建对象,避免使用new关键字
第二步:通过读取配置文件来获取要创建的对象的全限定类名
下面用一个小案例来初步解释下以上思想
解耦初步案例-springIOC原理分析
实行过程
1.创建一个Bean对象工厂
== bean在计算机英语中,是可重复使用组件的含义==
== javaBean是用java语言编写的可重复使用组件==
==javaBean > 实体类 ==
2.需要一个配置文件来配置我么你需要的类
文件类容:唯一标识:全限定类名(key-value)
配置文件可以是xml也可以是properties
3.通过读取配置文件中的类容反射创建对象
代码
- 模拟保存服务层和dao层代码以及主方法
package edu.yjsj.impl;
import edu.yjsj.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存成功!");
}
}
package edu.yjsj.impl;
import edu.yjsj.dao.IAccountDao;
import edu.yjsj.factory.Beanfactory;
import edu.yjsj.service.IAccountService;
public class AccountServiceImpl implements IAccountService {
//IAccountDao ad = new AccountDaoImpl();
IAccountDao ad = (AccountDaoImpl)Beanfactory.getBean("accountDao");
public void saveAccountService() {
ad.saveAccount();
}
}
由注释可以看出来本来需要new 的对象采用了调用工厂类方法创建对象,从而降低了类之间的耦合,达到了解耦的效果
package edu.yjsj.impl;
import edu.yjsj.dao.IAccountDao;
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存成功!");
}
}
2.工厂类:读取properties文件反射创建对象
package edu.yjsj.factory;
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 props;
private static Map<String,Object> beans;
//使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
props = new Properties();
beans = new HashMap<String, Object>();
//获取properties文件流对象
InputStream in = Beanfactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//取出配置文件的所有key
Enumeration keys = props.keys();
//遍历枚举对象
while (keys.hasMoreElements()){
String key = keys.nextElement().toString();
String beanPath = props.getProperty(key);
Object value = null;
try {
value = Class.forName(beanPath).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
beans.put(key,value);
}
} catch (IOException e) {
throw new ExceptionInInitializerError("初始化properties文件失败");
}
}
public static Object getBean(String beanName){
Object bean = beans.get(beanName);
return bean;
}
}
本段代码采用了class类方法读取properties文件。详细参考文章首部图