Factory Design Pattern

It is responsible for creating the objects. As name depicts, it is a factory for creating any specific kind of objects. It abstracts the user from the details of creation mechanism, and also abstracts the actual implementation class of instantiated object. The only requirement is that the ‘object to create’ should be of some already defined type. The actual implementation may differ based on the current scenario.


Example

  • Maruti Car Factory Object: We can ask this object to return us a Maruti car based on any runtime parameter which defines its model like Wagon R, or Esteem. It is the responsibility of this factory object to return us required car implementation based on specific parameters.
  • Row Renderer Factory Object: We can ask it to return the renderer like structured row renderer, or a designable row renderer.
When to Use
  • We can’t decide in advance that which class of object we may require at runtime, however type is known. So the type is known but the implementing class may vary depending upon runtime scenario.
  • We want to localize the knowledge of object creation into some class, so that responsibility resides with one object only.
  • We want to make the system configurable and extensible and so want to program to interface not to implementation.

Usage
  • We are free from object creation and choosing the right implementing class. This responsibility can be owned by the framework, and developers can work to interface following certain guidelines.
  • The mechanism for choosing the right implementing class can be made very configurable by using some configuration files (INI or XML).
  • Programming to interface rather than to concrete class so enabling extensibility of the system.

People who read this post also read :



3 comments:

Murali p said...

Great sir.... it could be very helpful, if some sample code is present for all design patterns.

Thanks

Saurabh Dixit said...

Thanks for nice article. Could you please describe difference between Abstract factory and factory design pattern.

Mohit Gupta said...

Abstract Factory is like another level of abstraction to create factory itself. Refer to other blog in same series for it.

Post a Comment