Thursday, January 2, 2014

Factory Design Pattern



In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.


  • creates objects without exposing the instantiation logic to the client.
  • refers to the newly created object through a common interface


The factory pattern can be used when:
  1. The creation of an object makes reuse impossible without significant duplication of code.
  2. The creation of an object requires access to information or resources that should not be contained within the composing class.
  3. The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
Factory methods are common in toolkits and frameworks, where library code needs to create objects of types that may be subclassed by applications using the framework.
Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.
Factory methods are used in test-driven development to allow classes to be put under test




Creates objects without exposing the instantiation logic to the client. Refers to the newly created object through a common interface

Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects

This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application architecture. Loose coupling can be introduced in application architecture by programming against abstract entities rather than concrete implementations
  
The basic principle behind this pattern is that, at run time, we get an object of similar type based on the parameter we pass.

No comments: