Monday, 7 November 2011

Factory Method Pattern

Name : Factory Method Pattern

It's easy to think of factories in the real world - a factory is just somewhere that items gets produced such as cars, computers or TVs. In the same way, the Factory method is a pattern used to facilitate the creation of other objects. Factory method is also known as virtual constructor.

Context:

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • Defining a “virtual” constructor.
  • Refers to the newly created object through the common interface.

Problem:

A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation.

Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that it must create. The Application (or framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the Application class may only know when it has to instantiate a new Object of a class, not what kind of subclass to create.

  • a class may want it's sub classes to specify the objects to be created.
  • a class may delegate responsibility to one of several helper sub classes so that knowledge can be localized to specific helper sub classes.

Solution:

Factory Method is a creational pattern. This pattern helps to model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate. We call this a Factory Pattern since it is responsible for "Manufacturing" an Object. It helps instantiate the appropriate Subclass by creating the right Object from a group of related classes. The Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code.

  • Factories have a simple function: Churn out objects.
  • Obviously, a factory is not needed to make an object. A simple call to new will do it for you. However, the use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific sub classes which create them.

The Factory Pattern is all about "Define an interface for creating an object, but let the sub classes decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" . "The Factory Method lets a class defer instantiation to subclasses".

The roles of Factory Method pattern:

The Factory Pattern has a couple of roles - a Creator and aConcrete Creator. This pattern is used when a class (theCreator) does not know beforehand all the sub classes that it will create. Instead, each subclass (the Concrete Creator) is left with the responsibility of creating the actual object instances.

No comments:

Post a Comment