jQuery in Action, 3rd edition
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why use Factory classes?" Watch "Why use Factory classes?" New topic

Why use Factory classes?

John Summers
Ranch Hand

Joined: Oct 06, 2003
Posts: 125
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?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.
I agree. Here's the link: http://aspose.com/file-tools
subject: Why use Factory classes?
It's not a secret anymore!