Design Patterns in Ruby: Template Method
A clear example of the Template Method pattern
A clear example
According to the GoF, the intent of the Template Method pattern is to:
“Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.”
In the example below, the #build_car method of the CarBuilder class defines an algorithm containing a step which is expected to vary, the #add_engine method. Therefore, we’ve elected to apply the Template Method pattern to the #add_engine step. It is to be defined in derivatives (subclasses) of the CarBuilder class.
Inheritance vs Composition
Because the Template Method design pattern uses inheritance instead of composition, it should be used frugally. Some people believe that it is best to vary the whole algorithm, leveraging composition, by applying the Strategy pattern instead. Realistically, there is nothing wrong with inheritance. You should happily leverage inheritance in instances where its benefits outweigh its trade-offs.
Strategy vs Template Method: which one to use?
Use the Strategy pattern when you want to vary an entire algorithm. Use the Template Method when you want to vary steps of an algorithm.
Abstract methods in Ruby
Ruby does not have abstract methods, which is why in the above example, we simply raise an error should the #add_engine template go undefined in any derivative (subclass) of the CarBuilder class.
The Template Method pattern is merely one of several helpful design patterns. To learn more, check out the seminal work on Design Patterns: The GOF Design Pattern book.