I have a concrete DAOFactory to create a bunch of DAOs. I need to call DAO2.method2 from DAO1.method1
For this I need to get reference to DAOFactory and then call createDAO2 to get DAO2 instance - from withing DAO1.method1
Straight forward solution is
to instatiate DAOFactory in DAO1.method1,
then call DAOFactory.createDAO2 and
then call the DAO2.method2
I am not sure if I should be creating so many instances of DAOFactory from underlying DAOs.
One solution I am thinking of is making all the create methods in DAOFactory static so that DAO1 doesn't have to get reference to DAOFactory in order to create the DAO2 and then to call method on it.
Any pitfalls or advice for or against this thought process? Thanks,
In my opinion implement DAOs as Singleton. That way you dont have worry about object creation but still have the advantage of inheritance.
And then of course you cant have instance variables in DAO class and getInstance must be synchronized.
Making DAOFactory Singleton makes sense.
Jeetendra, are you suggesting that I should also make all the DAOs which the DAOFactory will be creating singleton too?
I was suggesting DAOs as Singleton and not the Factory. Once you have DAO as singleton, you wont need a factory to create it.
My thought was more inline with the way Struts implements Action class and Web Container implements servlets.
Any threading issues you can think of
The advantage of a factory is that you can easily switch implementations of your DAOs without having to change client code. For example, you can implement your factory so that it returns implementation classes of DAO interfaces. The implementations can be configured in an XML file. In this way, you can easily switch your DAO layer for unit testing from a JDBC or Hibernate implementation to a data-in-class or file-based DAO, simply by changing the value of the XML configuration for the factory.
With this pattern you can also still use Singleton DAOs if you wish. Just have the Singleton factory call the Singleton construction methods in the DAO interface.
The Spring framework is built upon this idea of using an XML configuration file to specify inter-bean dependencies; it might be worth a look. One of the many advantages it offers is the ability to switch a dependency from a Singleton to a non-Singleton (called a "prototype" in Spring lingo) implementation with just a change of an XML attribute. If you were to use Spring, it would act as your factory.
Just implement your DaoFactory as a singleton, then you won't need to worry about multiple DaoFactory instances. Is there any advantage in your code to having multiple DaoFactories? If not, use a singleton.