views:

176

answers:

4

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.

+3  A: 

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;-).

Alex Martelli
Dependency Injection seems to be one of the things that the GoF book assumed
kyoryu
A: 

1-Easy to implement.

2-Client application code doesn’t have to change drastically.

3-Class creation is abstract from the client code.

You can also check this thread http://stackoverflow.com/questions/69849/factory-pattern-when-to-use-factory-methods

Prakash Kalakoti
Thanks. I was rather fond of that answer :)
kyoryu
+2  A: 

You have various advantages with factory method

  1. You can avoid creating duplicate objects (If your objects are immuatble) 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 obeject is the factory)
naikus
A: 

The basic idea behind it is to control creation.

The client calls a Method
object Factory.GetObject(Spec spec)

Now the factory is an abstraction that prevents the clients from hardcoding/baking in the class constructors into their code. Instead they call into the factory, the factory decides the right subclass of object to create based on the spec.

This approach is more extensible and resilient to change - in the future,

  • you could add a new adjustment parameter to the Spec and handle it within the factory method to return the LatestAndGreatestSubclass
  • you could improve an existing object and return v2 of the previous subclass or swap with an entirely different implementation : the existing clients and the factory method interface wouldn't have to change.

The comment got too long... So had to post it as an answer.

Gishu