通过使用工厂模式,实现了表现层——业务层以及业务层——持久层的解耦。例子中的表现层和持久层功能只是简单的模拟一下,不是重点。
第一步:配置文件
创建一个peporties文件
accountService=com.service.impl.AccountServiceImpl
accountDao=com.dao.impl.AccountDaoImpl
第二步:创建Factory
public class BeanFactory {
//定义一个properties对象
private static Properties properties;
//定义一个map,用来存放我们要创建的对象,我们把它称之为容器
private static Map<String,Object> beansMap;
//使用静态代码块为Properties对象赋值
static {
//实例化对象
properties = new Properties();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.Properties");
try {
properties.load(in);
beansMap = new HashMap<String ,Object>();
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存入容器中
beansMap.put(key,value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
//根据bean的名称获取bean对象
public static Object getBean(String beanName){
return beansMap.get(beanName);
}
第三步:业务层和持久层
持久层及其实现类
public interface IaccountDao {
void saveAccount();
}
============================
public class AccountDaoImpl implements IaccountDao {
@Override
public void saveAccount() {
System.out.println("保存成功!");
}
}
业务层及其实现类
public interface IaccountService {
void saveAccount();
}
===================================
public class AccountServiceImpl implements IaccountService {
// IaccountDao dao = new AccountDaoImpl();
IaccountDao dao = (IaccountDao) BeanFactory.getBean("accountDao");
@Override
public void saveAccount() {
dao.saveAccount();
}
}
最后简单的测试
public class Client {
public static void main(String[] args) {
//IaccountService service = new AccountServiceImpl();
for(int i=0; i<5;i++){
IaccountService service = (IaccountService) BeanFactory.getBean("accountService");
System.out.println(service);
service.saveAccount();
}
}
}
由于在beanFactory中把根据beanPath获取bean对象写在了静态代码块中,所以即使循环获取bean对象,也是只有一个!(单例)