Template Design Pattern [Behavioral]

Context: The template method pattern is useful when you need to allow third parties to provide or replace some steps of an algorithm while other parts remain fixed.

  • The fixed functionality is provided by the base type and can be overwritten.
  • The base type can provide so-called hook methods.
  • The hook methods may have default or empty implementations in the base type.
  • Clients can extend or override the behavior provided by the hook methods.
  • The hook operations get called at specific points.

The template method pattern allows extensions only at these predefined point so that clients can override certain steps of an algorithm without modifying its original structure.

The template method allows specific steps in an algorithm to be replaced by clients without modifying its original structure.

The template method defines the steps of an algorithm and allows some of the required steps to be modified.

Example: An employee of the organisation. The employee class would be the base template class. This template class will define hooks like check-in, break, work, check-out etc., with default implementations for them. Then there will be subclasses like Trainee, Software Developer, Lead, Architect, Manager. The work hook can be overridden by each subclass as per their job needs.

Unlike the strategy, this pattern is not about replacing the entire algorithm, but rather about changing certain steps of an algorithm. The fixed functionality is kept in the base type and cannot be modified by subclasses or conforming types. For the steps that can vary, there are extension points also known as hook operations.

Don’t use this pattern if you need to allow changing the entire algorithm. For the latter, use the strategy pattern instead.

Advertisements

One thought on “Template Design Pattern [Behavioral]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s