|
我们怎么设计自己的DAO层的呢?
看下示例,比如我要保存User对象,那么运用工厂模式和单例模式来设计DAO层。
DAO层接口:
package com.lwf.dao;
public interface IBaseDao {
void save(Object object);
}
DAO层接口实现,分MYSQL和ORACLE的实现
package com.lwf.dao;
public class BaseDao4MySql implements IBaseDao {
public void save(Object object) {
System.out.println("BaseDao4MySql");
}
}
package com.lwf.dao;
public class BaseDao4Oracle implements IBaseDao {
public void save(Object object) {
System.out.println("BaseDao4Oracle");
}
}
工厂类,利用工厂得到DAO
package com.lwf.dao;
public class BaseDaoFactory {
private static BaseDaoFactory baseDaoFactory = new BaseDaoFactory();
private String baseDaoName;
private BaseDaoFactory(){
baseDaoName = "BaseDao4MySql";
//加载xml属性
}
public static BaseDaoFactory getInstance(){
return baseDaoFactory;
}
public IBaseDao getBaseDao(){
IBaseDao iBaseDao = null;
if(baseDaoName.equals("BaseDao4MySql")){
iBaseDao = new BaseDao4MySql();
}else if(baseDaoName.equals("BaseDao4Oracle")){
iBaseDao = new BaseDao4Oracle();
}
return iBaseDao;
}
}
具体的业务:用户管理类:
package com.lwf.manager;
import com.lwf.bean.User;
import com.lwf.dao.BaseDaoFactory;
import com.lwf.dao.IBaseDao;
public class UserManager {
private static BaseDaoFactory factory = BaseDaoFactory.getInstance();
private static IBaseDao baseDao = factory.getBaseDao();
public static void save(User user){
baseDao.save(user);
}
}
用户类:model
package com.lwf.bean;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
下面是调用用户管理类的客户:
package com.lwf.client;
import com.lwf.bean.User;
import com.lwf.manager.UserManager;
public class Client {
public static void main(String[] args) {
User user = new User();
user.setAge(11);
user.setName("zhangshang");
UserManager.save(user);
}
} |
|