Java Behavioral Design Patterns – Template Method Design Pattern

In this article, we will understand one of the simplest design pattern: Template Method Design Pattern.This pattern falls under the behavioral design patterns.

The pattern provides the outline or skeleton of an algorithm. The algorithm structure is provided by an abstract class. This abstract class may choose to provide some default implementation. Few functionalities are defined abstract. Their implementation is deferred for subclasses as per the need but without changing the algorithm’s structure. Few key points to remember for this pattern:

  1. Common parts of an algorithm should be implemented only once in the base class.
  2. Subclasses can redefine the behavior of some of the functionalities without affecting the algorithm structure.
  3. The base class defines a final template method providing a uniform implementation of algorithm parts.

<Here are ALL other Java Design Patterns, explained in detail with examples>

Template Method Design Pattern by Example

For demonstration, let us assume an example where we will provide a service to open an email account.

Now the algorithm for this process can be:

  1. Accept desired email id
  2. Register the email id with chosen email provider
  3. Display confirmation message of email account creation.

In above algorithm step, 1 and 3 are common for all email provider and can be implemented by the base class. The second step will be unique to each email provider and they have to provide a specific implementation for that.

MailAccount Template Base class

Note that above base class defines a template method. This method is our complete algorithm. The method has been declared as final so no subclass can override and alter the algorithm flow.

GmailAccount Subclass

YahooAccount Subclass

Running the example

As I said earlier, this is one of the simplest patterns to implement. The output is:

Conclusion

In this article, we have understood Template Method Design Pattern. Few advantages of using this patten are:

  1. In this pattern, there will be no code duplication.
  2. Template pattern uses inheritance so we can reuse the code.
  3. This pattern provides flexibility to subclasses, so they can implement certain parts as per their specification.

You can download the code from our GitHub repository:

Download from Git

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

Add a Comment

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