Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why use Factory classes?

 
John Summers
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John Summers
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, makes sense now.
cheers.
john
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic