design-patternsbuildertemplate-method-pattern

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


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


Solution

  • The builder pattern

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

    Let's 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 every 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 create a complete car. Hence we can reuse an engine for every model if needed, and we can also customize each part of the car.

    Template method

    The template method, on the other hand, is used to abstract away some creations to avoid coupling implementations in your code against a specific framework/library (usually).

    For instance. You might have an IWebRequest interface, which can be implemented using WebSocketRequest or HttpRequest. Those implementations, in turn, are tightly coupled with the corresponding Response classes. If you want to support them, you have to have if statements in every place that you want to create them.

    if (request is WebSocketRequest)
      response = new WebSocketResponse();
    else
      response = new HttpResponse();
    

    With the template method, on the other hand, you can create the method IWebReponse in the IHttpRequest interface. In that way, all code that uses the requests is implementation agnostic.