This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Why use Factory classes? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why use Factory classes?" Watch "Why use Factory classes?" New topic
Author

Why use Factory classes?

John Summers
Ranch Hand

Joined: Oct 06, 2003
Posts: 125
Hi.
I notice a lot of APIs use Factory classes so that instead of doing:
Thing t = new Thing();
you do:
Thing t = ThingFactory.getThing();
What is the advantage of doing this?
thanks
john
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Usually, "Thing" is an interface or abstract class. There can be many different implementations or subclasses. Using the Factory patterns lets you get an instance of whatever implementation is appropriate. The Factory Method might choose among multiple implementations based on (for example) an external configuration file, or based on parameters you pass to the Factory Method itself.
One good example is the java.sql.DriverManager.getConnection() method, which give you a JDBC "Connection" object. Connection is an interface. Every JDBC driver supplies its own implementation. getConnection() chooses between drivers based on the connection string you pass as an argument, and returns that driver's implementation of Connection. You don't need to know anything about the class names that make up the driver, and using a different driver is just a matter of changing a String, which very often is something you load out of a runtime configuration file.


[Jess in Action][AskingGoodQuestions]
John Summers
Ranch Hand

Joined: Oct 06, 2003
Posts: 125
Ah, makes sense now.
cheers.
john
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why use Factory classes?
 
Similar Threads
abstactfactory vs factory method
Confused about RMI
Best way to "extend" or improve a bunch of objects
IOC Vs DI Vs Factory Pattern
using this in constructor