在实际开发过程中,为了防止耦合,实现一个dao层方法接口,业务层,从一个工厂间接获得dao层对象,工厂读取.properties文件,避免直接创建dao层对象,dao层只需实现接口方法即可
- .properties
CustomerDao=com.chen.customers.dao.impl.CustomerDaoImpl
- CustomerDao接口
public interface CustomerDao {
//完成客户信息的添加
void insertCustomer(Customer bean);
}
- dao层的CustomerDao接口实现类
public class CustomerDaoImpl implements CustomerDao {
//完成客户信息的添加
/* (non-Javadoc)
* @see com.chen.customers.dao.CustomerDao#insertCustomer(com.chen.customers.domain.Customer)
*/
@Override
public void insertCustomer(Customer bean) {
QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
String sql = "insert into customers values(?,?,?,?,?,?,?,?,?)";
Object[] params = {genereateID(),bean.getName(),bean.getGender()
,bean.getBirthday(),bean.getEmail(),
bean.getCellphone(),bean.getPreference(),
bean.getType(),bean.getDescription()};
try {
runner.update(sql,params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
- DaoFactory工厂类
/*
*这是一个工厂类
*
*/
public class DaoFactory {
public DaoFactory() {
// TODO Auto-generated constructor stub
}
//创建一个工厂的实例
private static DaoFactory instance = new DaoFactory();
public static DaoFactory getInstance() {
return instance;
}
//用于返回传进来的一个实例对象出来
//泛型,传进来一个类的字节码
public <T> T createDao(Class<T> t) {
//Teacher.class
String simpleName = t.getSimpleName();//Teacher
//读取一个配置文件: CustomerDao=com.chen.customers.dao.impl.CustomerDaoImpl
String clazzName = ResourceBundle.getBundle("dao").getString(simpleName);//com.chen.customers.dao.impl.CustomerDaoImpl
try {
return (T)Class.forName(clazzName).newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}