概述
- 在实际开发中要尽量避免各个代码成之间耦合度,要知道在高耦合度情况下会遇到这样的情况,修改某层代码可能会引起级联修改行为。
- 以xml和反射技术来解耦合
实现
配置XML文件
<?xml version="1.0" encoding="utf-8" ?>
<beans>
<bean id="CategoryDao" class="arjenlee.daoimpl.CategoryDaoImpl"/>
<bean id="ProductDao" class="arjenlee.daoimpl.ProductDaoImpl"/>
<bean id="UserDao" class="arjenlee.daoimpl.UserDaoImp"/>
<bean id="CategoryService" class="arjenlee.serviceimpl.CategoryServiceImpl"/>
<bean id="ProductService" class="arjenlee.serviceimpl.ProductServiceImpl"/>
<bean id="UserService" class="arjenlee.serviceimpl.UserServiceImp"/>
</beans>
使用工厂设计模式
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
/**
* Bean 工厂
*/
public final class BeanFactory {
public static Object getBean(String id) {
try {
SAXReader reader = new SAXReader();
InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("Beans.xml");
Document document = reader.read(is);
Element rootElement = document.getRootElement();
Element element = (Element) rootElement.selectSingleNode("//bean[@id='" + id + "']");
String clazz = element.attributeValue("class");
return Class.forName(clazz).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
使用
CategoryDao dao = (CategoryDao) BeanFactory.getBean("CategoryDao");