Design Pattern Download: The Template Method Pattern

Matthew MacFarquhar
1 min readMay 18, 2022

--

The Template Method Pattern is a Behavioral pattern used in software engineering when we want to create a super class with methods defined but allow our subclasses to overwrite it.

Example

Imagine we want to template out the behavior of a bunch of pets in a new video game, a lot of the functionality between pets is the same but there is also a few things that would be different (it would be quite strange to have a barking cat but most pets use the bathroom the same way). Instead of re-writing code for each type of pet (dog, cat, porcupine, etc…) we can define some methods in s super class and then — if needed — overwrite them in the subclasses.

When to use a Template Method?

  • When we want to make a bunch of subclasses with some shared functionality

What is the Template Method composed of?

  • The Template (pet class)
  • The Instances (dog and cat class)

Implementation

The Template

The Instances

Now we can play with our new virtual friends!

Pet pees on floor
Pet pees on floor
Dog wags its tail
Cat scratches you
you feed your pet
Cat does not eat food, it lives on your fear

--

--

Matthew MacFarquhar
Matthew MacFarquhar

Written by Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.

No responses yet