Saturday, August 17, 2019

Template Method Design Pattern

Template Method Pattern is a behavioral pattern. It basically involves defining a method called Template method which defines steps/skeleton of an algorithm and hence controls the overall execution of the algorithm. These individual steps are either implemented in same class or declared abstract so that sub-classes can provide suitable implementation. Template method is made final so that sub-classes can't temper with the structure of the algorithm.

Template method design pattern is heavily employed in development of frameworks. This design pattern helps a lot in avoiding code duplication. Also, algorithm is implemented at a single place and hence it is mush easier to make any changes. This gives much better control over any future modifications.

Code structure



Code setup consists of an abstract class and concrete classes extending the abstract class. Abstract class contains skeleton of the algorithm expressed in terms of a sequence of method calls with each method corresponding to a step in algorithm execution. Some of these methods may be implemented in abstract class and are final so that sub-classes can't change them. Other methods are declared abstract and sub-classes their implementation as per their needs. Template method too is declared final so that sub-classes can't change skeleton of the algorithm.

Some hook methods can also be provided. These are concrete methods but are either empty or provide default implementation. Sub-classes can override them if they want to. Hook methods are heavily used in frameworks, for example as life-cycle methods of various frameworks.

The Hollywood Principle and Template Method

The Hollywood Principle helps to avoid dependency rot in a software system. It basically means that low level components hook into a system but its high level components which decide when and how are low level components are needed. It is popularly phrased as "Don't call us, we will call you".

Template method design pattern also exhibits similar behavior. Parent class controls the flow of the algorithm and invokes sub-class methods whenever needed. Clients interact with parent class abstraction rather than a sub-class implementation. Sub-classes' role is just to provide specific implementations of the steps in algorithm while flow control is determined by parent class only.


No comments:

Post a Comment