面向接口编程+工厂模式+单例模式

当与数据库打交道,考虑到有各种各样的数据库,我们通常设计一个DAO接口与N个DAO类,DAO类实现DAO接口,在处理类中定义一个DAO接口,并在配置文件中设置这个接口使用的是哪个DAO类。

此种方法也叫控制反转。

当有好多接口时如UserDAO,CategoryDAO,ProductDAO时,我们通常设计一个DAO工厂FactoryDAO用来生产DAO(生产出来的DAO已经确定了是哪种数据库),这是一种设计模式,即工厂模式。

编写处理类时通常使用单例模式,试想一下多个婆婆管理你,肯定烦得不行,故使用单例模式

如ProductMgr中单例模式的使用如下:

private static ProductMgr pm = null;
 static {
  if(pm == null) {
   pm = new ProductMgr();
   //you should read the config file to set the special database
   pm.setDao(new ProductMySqlDAO());
  }
 }
 private ProductMgr(){}

//ProductMgr中只有这一个静态方法
 public static ProductMgr getInstance() {
  return pm;
 }

 当在别的地方调用ProductMgr中的非静态方法时使用如下代码:ProductMgr.getInstance().方法名();

posted on 2013-07-24 19:05  凯特的宝贝世界  阅读(215)  评论(0编辑  收藏  举报