DEV Community

jzfrank
jzfrank

Posted on

HFDP(8) - Template Method Pattern

Intro

Many of us are living on caffein beverages. Some of us drink coffee, some of us drink tea. Check out the steps needed to make a coffee:

  1. Boil some water
  2. Brew Coffee in boiling water
  3. Pour coffee in cup
  4. Add sugar and milk

and steps to make a tea:

  1. Boil some water
  2. Brew tea in boiling water
  3. Pour tea in cup
  4. Add lemon

We can already see there exists an underlying similar algorithm for the two processes, namely:

  1. Boil water
  2. Brew
  3. Pour in cup
  4. Add condiments

Of course, we may add different condiments to tea and coffee. That should be left for the subclass to implement.

So yes, this is it! Abstract the steps into a template method (encapsulating algorithms), then leaving specific step(s) in the algorithm to the subclasses. This is the intuition for our Template Method Pattern

Definition

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method let's subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

When we implement this, we usually declare the template method as final, and to-be-implemented methods as abstract. We also define one or many hook method, which are optional for the subclasses to implement.

Template Method Pattern

Design Principle

The Hollywood Principle

Don't call us, we'll call you.

This principle states that one should avoid the circular dependencies between up and low level components. -> Just let the high-level component controls the low-level components, but not the converse.

Examples

Template Method pattern is particularly useful in frameworks.

Java Arrays Sorting

Say we have an array of self-defined classes Duck, to use Sorting provided by Java, we need to make Duck implement Comparable interface and implement compareTo method.

Swing JFrame

JFrame's update algorithm calls paint(), But by default paint() does nothing. It is a hook and can(should) be overwritten.

Top comments (0)