Member-only story
Design Patterns in Go: Template Method
Behavioral Patterns target issues related to communication and interaction between objects. They focus on defining protocols for collaboration among objects that are often too complex to design statically, enabling dynamic delegation of responsibilities at runtime.
OK, Let’s go through the description of the 5th behavioral pattern — Template Method Pattern.
Context:
When designing an algorithm as a series of steps, some steps may be common across subclasses while others may vary. If we implement all steps in each subclass, there’s will be lots of duplicate code. This will increase the code complexity.
Solution:
The Template Method design pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It helps to encapsulate the invariant parts of an algorithm and let the subclasses implement the variable parts.
So, we can define an abstract base class that specifies a skeleton template method defining the algorithm steps. Some steps are implemented in the base class while others are abstract methods to be implemented in subclasses.
Here’s an example, we want to generate reports for some financial and educational area. We must collecte data, analyze data, finalize and generate the final…