This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am having DAO class(say FirstDAO) which is responsible for interaction with a specfied table (say Table1)in Database. This class interacts only with the specified table.
There is an helper class(say Helper1) which instantiates this DAO class to perform some operations.
Now I need to perform similar operations on a new Table(say Table2) which is again used by helper class (Helper1). I created another new new DAO class(Say SecondDAO) which is responsible for interactions with table2.
The table to be interacted depends on the user selections. For this i need to modify Helper1 as
Is this right to apply Factory Pattern for this problem? and is this the right way of applying Factory pattern for the identified problem?
This looks like a neat approach. Read up on Strategy Pattern because you're pretty much there. A couple suggestions ...
Minor nit: Work on the names. (Maybe this is just demo code and you've already done this in the real deal.) "create" gives away rather too much implementation detail. How about "get"? Then clients won't need to worry about whether "get" creates a new object, returns a singleton, returns something from a pool, or whatever. "useSelection" is pretty meaningless (to me) as well. Try to describe what it is that determines which DAO you get.
Bigger nit: Find a way for the "factory" (not exactly a GoF factory but close enough for me) to do something other than if/else tests to decide what to return. Maybe map keyed by the userSelection string and holding class names for a Class.forName(x).newInstance(). You could load the map contents from configuration. It would be very cool if you could write this class once and never touch it again, just add more keys & DAOs through config.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi