The template behavioral pattern allows your derived classes to change certain aspects of the base class behavior without needing to rewrite everything.

This design pattern is great when you have a complicated set of steps that the base class provides. You can then write derived classes that use the overall set of steps and only need to specialize certain smaller steps. The base class defines the overall structure of how something should be done and calls one or more virtual methods at the right time which a derived class can override.

The overall method in the base class is called the template method because it provides the structure. It acts like a template.

The methods that the derived classes override are called hook methods because they let a derived class insert custom behavior into the process sort of like how a hook can attach itself to something. It’s important to note that the derived classes can’t just insert their code anywhere. This whole pattern starts with the base class defining the overall template and the available hooks. If there are no hooks, then you don’t really have code that follows this design pattern.

There’s another common scenario that the template method can help with. It’s sometimes useful in derived classes to not just override a base class method but to extend a base class method. How does a derived class do this? First the method needs to be virtual so the derived class can override it. Then in the derived class implementation, it does whatever it needs to do and then calls the base class version.

But what happens if a derived class forgets to call into the base class? You end up with only the behavior in the derived class and the extension is lost. How can you make it less likely for this to happen? Just remove the need for the derived class to call the base class in the first place.

Instead of making a virtual method that a derived class overrides to extend, you instead define a normal non-virtual method in the base class. This method will follow the template design pattern and call a virtual method that a derived class can override. The base class performs its own behavior and then calls the virtual method. Or maybe it calls the virtual method and then performs its own behavior. The important part is that it does both. Now, when a derived class overrides the virtual method to extend the behavior, it doesn’t need to call the base class version of the virtual method anymore at all.


What's on your mind?
On a scale of 0 to 10, how likely are you to refer us to friends?