如何正确地将工厂方法应用于 DAO 工厂?

How to correctly apply factory method to the DAO factory?

the documentation about DAO中说:

When the underlying storage is not subject to change from one implementation to another, this strategy can be implemented using the Factory Method pattern to produce a number of DAOs needed by the application. The class diagram for this case is shown in Figure 9.3.

图9.3本身:

造成误解的是我们如何应用工厂方法来生成DAO数量?据我所知,DAO 可能看起来像

public interface DAOFactory{

    public DAO1 getDAO1();
    public DAO2 getDAO2();

}

但这不是工厂方法。这将是一个抽象工厂,因为我们正在生产一系列对象而不是单个对象。你不能解释一下他们说的是什么意思吗

this strategy can be implemented using the Factory Method pattern to produce a number of DAOs needed by the application. The class diagram for this case is shown in Figure 9.3.

你是对的。这是误导。 描述使用 Factory 方法 的图像当然是 Abstract Factory 设计模式的一个示例。只有一种工厂实现方式。

关于工厂方法和抽象工厂之间的区别,这里有一个很好的解释:Differences between Abstract Factory Pattern and Factory Method

文档中显示的图表描述了抽象工厂 模式。

我可以想象下面使用 DAOsFactory Method

// the Service contains the business logic and uses DAOs to access data
class BaseService {

   public Object doSomething() {
       return getDao().retrieveObject("identifier");
   }

   // Factory method producing DAOs
   public IDao getDao() {
       return new BaseDao();
   }

}

// The DAO interface
interface IDao {
    Object retrieveObject(String identifier);
}


// Another Service that overwrite the type of produced DAOs 
class SmartService extends Service {

   // overwrite the factory method
   public IDao getDao() {
       return new SmartDao();
   }
}