Wednesday 22 July 2015

The Factory Method Pattern

The Factory Method Pattern

 Defined


The factory  method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

As with every factory, the Factory Method Pattern gives us a way to encapsulate the instantiations of concrete types. Looking at the class diagram below, you can see that the abstract Creator gives you an interface with a method for creating objects, also known as the "Factory Method". Any other methods implemented in the abstract Creator are written to operate on products produced by the the factory method. Only subscribers actually implement factory method and create products.

As in the official definition, you'll often hear developers say that Factory Method lets subclasses decide which class to instantiate. They say "decides" not because the pattern allows subclasses themselves to decide at run-time, but because the creator class in written without knowledge of the actual products that will be create, which is decided purely by the choice of the subclass that us used.

- There is more to making objects than just using the new Operator.
- Seen a similar design where a factory is defined in a static method (Static factory).  whats the difference.  advantage of static method is you don't need to instantiate an object to make use of the create method. disadvantage that you cant subclass and change the behavior of the create method.

Factories handle the details of object creation.


Use me to decouple your client code from the concrete classes you need to instantiate, or if you don't know ahead of time, all the concrete classes you are going to need. To use me just subclass me and implement factory method.

Diagrams


Bullet Points
  • All factories encapsulate object creation.
  • Simple Factory, while not a bonafide design pattern, is a simple way to decouple your clients from concrete classes.
  • Factory Method relies on inheritance: object creation is delegated to subclasses which implement the the factory method to create objects.
  • Abstract factory relies on object composition. object creation is implemented in methods exposed in the factory interface.
  • All Factory Patterns promote, loose coupling by reducing the dependency of your application on  concrete classes.
  • The intent of Factory Method is to allow a class to defer instantiation to subclasses.
  • The intent of Abstract Factory is to create families of related objects without having to depend on concrete classes.
  • Factories are a powerful technique for coding to abstractions, not concrete classes.

No comments:

Post a Comment