利用工厂模式实现Dao层和Service的解耦
2015-08-14 20:15 怡红院丿无痕 阅读(677) 评论(0) 编辑 收藏 举报dao.properties的文件内容
UpfileDao=cn.itcast.dao.impl.UpfileDaoImpl
DaoFactory的实现
public class DaoFactory { private static Properties daoconfig = new Properties(); static{ try { daoconfig.load(DaoFactory.class.getClassLoader().getResourceAsStream("dao.properties")); } catch (IOException e) { throw new RuntimeException(e); } } private DaoFactory(){} private static final DaoFactory instance = new DaoFactory(); public static DaoFactory getInstance(){ return instance; } public <T> T createDao(Class<T> interfaceClass){ String name = interfaceClass.getSimpleName(); String daoClassname = daoconfig.getProperty(name); try { return (T) Class.forName(daoClassname).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } }
BusinessServiceImpl利用DaoFactory进行解耦
private UpfileDao dao = DaoFactory.getInstance().createDao(UpfileDao.class);