Friday, March 8, 2013

Factory Pattern and Singleton Patterns

Factory-
 - hide constructor(make it private)
 - expose a method which will provide you the required object.

advantages -
 - get rid of the repetition of "new" key word whenever we create objects.
 - abstract the implementation
whenever we provide some kind of library, its always good to provide a factory which will provide users the desired object, instead of exposing the class.

limitations -
 - private constructor will cause problem in inheritance

NOTE - making constructor protected will let us derive the class, but then we will have to provide the same getter method for subclass as well, else it will return the base object always, even if we call it on derived class.

Singleton-

 - only one instance of a class.
 - single instance, global access.

singleton vs static - singleton can be implemented using static as well. but static class can not implement any interface, unless interface is simply a marker.

limitations -
 - inheritance is not possible.
 - testing might become tricky. 

No comments:

Post a Comment