Template Pattern- Deep Dive(Java)

Vibhor Pareek
2 min readJul 2, 2021

--

Introduction

Template pattern is another behavioral design pattern which helps you to define a skeleton of steps to be performed for an algorithm. This pattern is mostly used where you see same steps being repeated and where template pattern comes to rescue to help you define loose coupling & single responsibility across your classes.

Problem Statement

Let’s take a simple use case where in you want to achieve below steps.

  • Extract data from databases/files/cloud storages.
  • Parse data according to your defined strategy.
  • Generate report from the parsed data.
  • Store reports again back to some data store.

As you can see above steps can be duplicated if we are trying to extract data from files/databases or any cloud storage.

If we follow template pattern, we will be able to structure our codebase and achieve loose coupling & srp, irrespective of any new storage which can get added in future.

Deep Dive

  • Let’s try to define template for our steps which will involve an abstract class as shown below containing abstract steps which needs to implemented by concrete classes.
Template Abstract Class
  • Now building concrete classes would be piece of cake now . Here is our Database class which implements above methods as below.
Concrete Class-1

Similarly, another class for file report generator is as follows

Concrete Class-2

We are done now and looking at the below client call seems so simple and classy.

Client Class

Take-Aways

  1. Your template method should be final so that implementing class can’t override and change the order of steps.
  2. You should mark all methods abstract which derived classes must implement.

Next time, while building a feature just think about steps being duplicated in your code and certain task is achieved via sequential steps. BOOM apply template and thank the creator later :) Happy Coding !

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vibhor Pareek
Vibhor Pareek

No responses yet

Write a response