Differences between builder pattern and template method (builder vs template)

Sandeep G B picture Sandeep G B · Apr 15, 2011 · Viewed 7.6k times · Source

Template pattern provides algorithm in the base class whose steps can be modified in the derived class. In Builder pattern, concrete builder exposes methods for building a product which are called from the Director class.

I understand there is difference with respect to the purpose of using these patterns. Template pattern is a behavioral pattern which changes one or more steps in a template whereas builder pattern is a Creational pattern.

Apart from the above said difference, are there any other differences?

Isn't director in builder pattern acting as a base template in template pattern. The concrete builders are acting like derived classes in the template pattern with substitutable steps?

Can someone please clarify. Thank you.

I am referring http://www.dofactory.com/Patterns/Patterns.aspx

Answer

jgauffin picture jgauffin · Apr 15, 2011

Template method is really just a way to define some methods that each subclass must define.

The builder pattern is used to construct a more complex object.

Lets say that we want to construct different Saab (car brand) models. Each model has different engines, lights etc.

If we were to use the template method pattern we had to create one class for each single combination of cars or use some nasty inheritance hierarchies. A lot of those methods would also contain duplicate code.

With the build pattern we can instead take different parts and compose those together to a complete car. Hence we can reuse a engine for every model if needed and we can also customize each part of the car.