利用工厂模式实现serveice和dao层的解耦,这样就可以不用在service层实例化dao层的对象,当dao层代码发生改变的时候(数据库实现发生改变)直接修改配置文件就不用改变service层的代码。
配置文件:dao.properties
UserDao="com.dao.UserDaoJdbcImp" 如果是oracle实现就可以修改配置文件就行
源代码:DaoFactory.java
package com.demo; import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import org.hamcrest.Factory; //利用工厂模式实现业务层与DAO层解耦
public class DaoFactory {
11 private static Properties daoConfig = new Properties();
private static DaoFactory factory = new DaoFactory();
private DaoFactory(){
//加载配置文件
15 InputStream in = DaoFactory.class.getClassLoader().getResourceAsStream("dao.properties"); try {
daoConfig.load(in);
} catch (IOException e) {
throw new RuntimeException();
}
} //获取工厂对象
public static DaoFactory getInstance(){
return factory;
} 29 public static <T> T createDao(Class<T> clazz){//这里传进来的是DAO接口
30 String name = clazz.getSimpleName();//UserDao
31 String className = daoConfig.getProperty(name);
32 try {
33 T dao = (T) Class.forName(className).newInstance();
34 return dao;
35 } catch (Exception e) {
36 throw new RuntimeException(e);
37 }
38 }
}