“Factory Method is a specialization of Template Method”. How

design-patternsfactory-methodobject-oriented-designtemplate-method

Similarities and differences between the two:

Template Method

  • Relies on inheritance.
  • Defines the steps of an algorithm, and leaves the task of implementing them to subclasses.

Factory Method

  • Relies on inheritance.
  • A superclass defines an interface to create an object. Subclasses decide which concrete class to instantiate.

The two side by side:

enter image description here

I'm not sure what the phrase "Factory Method is a specialization of Template Method" means (it's in the Head First Design Patterns book). In Beverage we have the method prepare which is final and defines a series of steps. In PizzaStore we have a method which is abstract, and subclasses redefine it. How is the latter a specialization of the former?

Best Answer

In Beverage we have the ("template") method prepare which calls some abstract methods like boilWater, brew etc. which are implemented in the subclasses. It is not essentially for the pattern to have the template method located in the base class, it could be anywhere else, assumed the abstract methods are public. But it is essentially that there are the abstract methods which must be overriden and will fill the gaps in the "algorithm template".

The factory method is also about a class where abstract methods are overwritten, a core point is the caller of that method does not need to know the exact type of the created object. Note that in PizzaStore, the abstract method createPizza must be called somewhere from - lets say a method createLotsOfPizza.

This makes the latter a template method, where the specific steps of the "algorithm to create pizzas" are the gaps to be filled. Now it is probably just an imprecise use of words by saying "the factory method pattern" is a special case of the "template method" pattern. Especially the "factory methods" are not "template methods", however they might be called from a template method. So to be more precise, we might say

"the factory method pattern is typically used in conjunction with a special case of the template method pattern"

and I guess that is what the authors of that book wanted to express.

Related Topic