Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

Why use Factory classes?

 
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
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • 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
 
Popeye has his spinach. I have this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!