Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should one use factory method to create objects [duplicate]

Possible Duplicates:
Factory Pattern. When to use factory methods?
Why do static Create methods exist?

Though I know what is Factory Design Pattern. But I am unable to comprehend what are the benefits of using it. Why should we create objects using Factory Design Pattern.

like image 528
Vaibhav Jain Avatar asked Jul 28 '10 04:07

Vaibhav Jain


2 Answers

By creating objects through factories, you avoid making the subsystem's code depended on specific implementations of the interfaces it uses -- "program to an interface, not to an implementation" is the most important single phrase in the "Design Patterns" book, and factories are one crucial way to move your code towards that excellent goal (dependency injection is another key DP for that, which the classic book does not cover -- but then, often the dependencies you inject are factories anyway, so that omission is not too horrible;-).

like image 101
Alex Martelli Avatar answered Sep 20 '22 06:09

Alex Martelli


You have various advantages with factory method

  1. You can avoid creating duplicate objects (if your objects are immutable). The factory can return the same object for same set of parameters.
  2. You can create and return any subtype of the type that factory is designed to create. Replacing implementations without changing client code (calling code).
  3. You can return same object every time (in other words, singleton if the only way to get the object is the factory).
like image 33
naikus Avatar answered Sep 23 '22 06:09

naikus