The Factory Method Design Pattern is a creational design pattern that allows you to customize a class behavior by overriding the method used to create an object with which the class will collaborate. We can say that the Factory Method Design Pattern is like the Template Method Design Pattern but for creating the objects instead of encapsulating the algorithms. Look at the following example:
By moving the “new” operator usage under the method, which can be overridden, we gained the flexibility of deciding which object will be created in a child class. Factory Method will also require a common interface to be implemented by objects created by the Factory Method. This is for the business-related method to work transparently with the object that is created.
The Factory Method resist in the class that provides some kind of business logic. In the above example, the shopping cart should give us the ability to calculate cart totals, including the shipping cost. Those cost calculations are part of business logic, which at some point requires the Factory Method to create an object that will provide a shipping method class, that will be used to calculate international or domestic shipping costs. So Factory Method is usually defined in the class, which uses it in some business flow that requires flexibility on collaborator creation.
To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: