持久层设计

来源:互联网 发布:sql inner join 编辑:程序博客网 时间:2024/05/25 20:01

DAO:Data Accessor:数据存储接口。将数据访问层封装起来。
    Active Domain:对象封装。
Data Accessor Object (DAO)=Data +Accessor +domain Object;
public class CustomerDAO{
 public static Customer getCustomer(String id){...}
 public void save(Customer customer){...}
}
Factory模式:
public calssDAOFactory{
 private static HashMap daomap=null;
 public static Object getDAO(Class daoInterface){
 initial();
 Object dao=daomap.get(daoInterface);
 IF(NULL==DAO){throws new DAOException(...);}
 return dao;
}
public static synchronized void inital(){
 if(null=daomap){
  daomap=DAOConfig.load();}
}
}
public class DAOConfig{
 private static Logger logger=LogManager.getLogger(DAOConfig.calss);
 private static final String DAO_CONFIG_FILE="dao.xml";
 private static final String DAO_CONFIG_SECTION="DAO";
 public static synchronized HashMap load(){
  HashMap map= new HashMap();
  JFigLocator j = new JFigLocator(DAO_CONFIG_FILE);
  JFigif daoConfig = jfIG.GETiNSTANCE(J);
  Properties prop = daoConfig.getSectionAsProperties(DAO_CONFIG_SECTION);
  Enumeration e = prop.keys();
  while(e.hasMoreElements()){
    String daoIface = (String ) e.nextElement();
    String daoImpl=prop.getProperty(daoIface);
  try{
     Class iface=ClassToolKit.loadClass(daoIface);
     Class impl=ClassToolKit.loadClass(daoImpl);
     map.put(iface,impl);
    }catch(ClassNotFoundException e){
      logger.debug("");
    }
 }
return map;
}
}
配置文件:
<configuration>
 <section name="DAO">
  <entry key".....CustomerDAO" value="">
 </section>
</configuration>
动态加载一个类
 class ClassToolKit {
 public static Class loadClass(String className) throws ClassNotFoundException{
  Class cls=null;
  try{
   cls=Thread.currentThread().getContextClassLoader().loadClass(className);
   
  }catch(Exception e){
   e.printStackTrace();
  }
  if(cls==null){
   cls=Class.forName(className);
  }
  return cls;
  
 }

}
业务层改进:
CustomerDAO customerDAO=(CustomerDAO) DAOFactory.getDAO(CustomerDAO.class);
customer customer=customerDAO.getCustomer(customerID);