简单地说,软件工程中对象之间的耦合度就是对象之间的依赖性。指导使用和维护对象的主要问题是对象之间的多重依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。
文件结构
Dao
public interface IAccountDao {
void saveAccount();
}
DaoImpl
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("账户保存实现了");
}
}
Service
public interface IAccountService {
void saveAccount();
}
ServiceImpl
public class AccountServiceImpl implements IAccountService {
//private IAccountDao accountDao = new AccountDaoImpl();
//使用反射方式,替代直接调用AccountDaoImpl
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
public void saveAccount() {
accountDao.saveAccount();
}
}
表现层Client
public class Client {
public static void main(String[] args) {
//IAccountService accountService = new AccountServiceImpl();
IAccountService accountService = (IAccountService)BeanFactory.getBean("accountService");
accountService.saveAccount();
}
}
工厂BeanFactory
public class BeanFactory {
//读取配置文件
private static Properties properties;
//定义一个容器map,用于存放我们要创建的对象
//单例模式
private static Map<String, Object> beans;
static {
try {
properties = new Properties();
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(in);
/* 单例模式 */
//实例化容器
beans = new HashMap<String, Object>();
Enumeration<Object> 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();
//存入容器map
beans.put(key, value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据Bean的名称获取bean对象
* 单例模式
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return beans.get(beanName);
}
///**
// * 根据Bean的名称获取bean对象
// * 多例模式
// * @param beanName
// * @return
// */
//public static Object getBean(String beanName) {
// Object bean = null;
// try {
// String beanPath = properties.getProperty(beanName);
// bean = Class.forName(beanPath).newInstance();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return bean;
//
//}
}
配置文件bean.properties
accountService=com.ouyang.service.impl.AccountServiceImpl
accountDao=com.ouyang.dao.impl.AccountDaoImpl