前置
耦合:程序之间的依赖。包括类之间的依赖、方法之间的依赖。
解耦:降低程序之间的依赖。
开发中解耦的目标:尽量做到编译期不依赖,运行时依赖
解耦的思路:
1、通过反射的方式创建对象,尽量避免使用new关键字创建对象。
2、通过读取配置文件获得要创建对象的全限定类名。
3、通过工厂模式,以JavaBean的形式来创建对象。(JavaBean的意思是Java语言编写的可重用组件)
代码示例
1、JavaBean组件的配置文件
需要在程序中以new的形式创建实例的JavaBean,以key=value的形式保存到配置文件中,假设命名bean.properties
demoService=com.hisense.service.impl.DemoServiceImpl
demoDao=com.hisense.dao.impl.DemoDaoImpl
2、创建可以生产Bean对象的工厂
/**
* @author : sunkepeng E-mail:sunkepengouc@163.com
* @date : 2020/8/25 17:22
* 创建一个生产JavaBean对象的工厂,用工厂来生产service和dao接口的实例化对象
*/
public class BeanFactory{
// 定义properties对象
private static Properties props;
// 定义Map用于存储创建的Bean对象
private static Map<String,Object> beans;
static{
try {
props = new Properties();
// 实际开发中加载配置文件用类加载器、或者servletContext
InputStream ins = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(ins);
beans = new HashMap<String,Object>();
// 取出配置文件中的所有key,并通过key获取对应全限定类名存入Map中
Enumeration keys = props.keys();
while(keys.hasMoreElements(){
String key = keys.nextElement().toString();
String beanPath = props.getProperty(key);
// 此处通过反射的形式创建对象
Object value = class.forName(beanPath).newInstance();
// 把key、value存入到容器中
beans.put(key,value);
}
} catch(Exception e){
throws new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据bean的名称获取对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
3、service和dao的接口及实现类
持久层:
public interface DemoDao {
/**
* 模拟保存
*/
void saveDemo();
}
public class DemoDaoImpl implements DemoDao {
public void saveDemo(){
System.out.println("执行了数据库操作");
}
}
业务层:
public interface DemoService {
/**
* 模拟保存
*/
void saveDemo();
}
public class DemoServiceImpl implements DemoService {
// 使用new的方式创建dao的实例化对象
//private DemoDao demoDao = new DemoDaoImpl();
// 使用工厂生产dao实例化对象
private DemoDao demoDao = (DemoDao)BeanFactory.getBean("demoDao");
public void saveDemo(){
demoDao.saveDemo();
}
}
4、表现层调用业务层逻辑
public class Web {
// 启动入口
public static void main(String[] args) {
// 使用new的方式实例化service
// DemoService demoService = new DemoServiceImpl();
// 使用工厂生产service实例
DemoService demoService = (DemoService) BeanFactory.getBean("demoService");
demoServicesaveDemo();
}
}
总结:
通过工厂模式,用读取字符串的形式,从配置文件中读取接口实现类的全限定类名,用反射的方式实例化对象,避免了通过 new 关键字产生的类之间的依赖关系,实现了程序的解耦。