Wednesday 6 November 2013

Understanding Factory Methods

I have myself been using factory methods for a while now and it would be factually incorrect to tell you that I never cared to understand why I used them as against plain constructor "new" method of object instantiation. Nevertheless, I must definitely admit that I would have read about them several times but wasn't really fortunate to remember all these benefits clearly. This called on me to write a post regarding the same so that it would get entrenched in my head thereafter.

Now, let's quickly get started:


  • The use of getInstance() or valueOf() in a factory design pattern helps you to procure a reference to an object of a type without having to explicitly worry about the sub-type of the object returned. Hazy? It surely would be no better with an explanation of this sort. Now, let me dig deeper.
Consider an interface, "Car" which is implemented by "Mazda" and "Sedan". Now, it is fairly clear that both of these are cars themselves and as such, one can do with a reference to an object of either Mazda or Sedan when one needs to procure a reference to an object of Car type. So, it's fairly clear that the application of a framework such as Spring in Java that relies on Dependency Injection (which can be understood more simply as some form of Late Binding or Run-time Binding ) can exploit this compile-time abstraction and as such benefit from the same.

  • Among other benefits, what interests me most is an idea based upon an extension to the factory pattern which limits the number of objects of a class to one. Such a class is called a Singleton and it is typically a means to reuse existing class objects where possible rather than creating new ones. Thus, it is not difficult to understand that this is in keeping with memory efficiency. 

No comments:

Post a Comment