Template method design pattern

Description:

This is a type of behavioral design pattern. There is an operation in a parent class which has few sub-tasks and all or few sub-tasks behavior may be changed by its child classes at run time.

It means we are defining a structure of an operation / algorithm and we are allowing child classes to implement their own behavior.

Example:

Let’s take an example of bank account. We need to calculate interest rate at the end of some period. so there are few steps we need to perform.

  1. Need to retrieve balance from database / source
  2. Need to calculate interest rate with balance
  3. Update balance into database / source

So here, step 1 and 3 will remain same for all types of account however, step 2 may differ so each type of account will implement its own behavior.

Template method design pattern
Template method design pattern1

Structure:

Structure_Template method design pattern

Advantages:

  1. When algorithm behavior will be changed, then each sub classes will handle their behavior by themselves.
  2. Code duplication will be reduced.

Leave a Reply

Your email address will not be published. Required fields are marked *