Wednesday, September 24, 2014

Factory Method Pattern

All factory patterns encapsulate object creation.

The Factory Method pattern encapsulates object creation by letting sub-classes decide what objects to create.

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.

Creator is not tightly coupled to any ConcreteProduct.







Franchising the pizza store

Each franchise might want to offer different styles of pizzas (New York, Chicago, and California) depending on where the franchise store is located and the tastes of the local pizza connoisseurs.

Approach 1



Approach 2

What if franchises were using your factory to create pizzas, but starting to employ their own home grown procedures for the rest of the process: they'd bake things a little differently.

You would really want to create a framework that ties the store and the pizza creation together, yet still allows things to remain flexible. 

Framework for the Pizza store







Declaring a factory method

A factory method handles object creation and encapsulates it in a subclass. This decouples the client code in the superclass from the object creation code in the subclass.


We have gone from having an object handling the instantiation of our concrete classes to a set of subclasses that are now taking on that responsibility.




No comments:

Post a Comment