File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes OO, Patterns, UML and Refactoring and the fly likes Is it right to apply Factory Pattern for this scenario? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Is it right to apply Factory Pattern for this scenario?" Watch "Is it right to apply Factory Pattern for this scenario?" New topic

Is it right to apply Factory Pattern for this scenario?

Ajay Xavier
Ranch Hand

Joined: Jan 03, 2005
Posts: 109

Problem scenario:

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?

Thanks in advance,

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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
I agree. Here's the link:
subject: Is it right to apply Factory Pattern for this scenario?
It's not a secret anymore!