Pattern of the Week: Template Method

This is the fourth in a series of “Pattern of the Week” posts. I’m primarily sticking with the Gang of Four patterns, but I may branch off occasionally. Thanks for reading.

Type: Behavioral

This week’s pattern is the Template Method pattern. This pattern allows you to define a set of algorithms that follow the same procedure, but that might have certain parts that differ. For this pattern, I’m borrowing heavily from my post on the Strategy Pattern, so if you haven’t read it yet, you should read that one first.

Alright, let’s look at a template method:

This method, called Attack(), defines a basic algorithm of attack. First, we print out the warrior’s name (as a battle cry?), then we get that warrior’s weapon of choice, and finally, we use the weapon. Here’s the rest of the Warrior abstract class:

We use this abstract Warrior class to define specific types of Warriors, like this one:

As you can see, the derived class “fills in the blanks” of the template method, by defining what the GetWarriorName() and GetWeaponOfChoice() methods do. We’re filling in the blanks of the template by using inheritance. When we call the Attack() method, the methods defined in the derived class are called, completing the algorithm for the type of Warrior we’re using.

This is pretty much all there is to the Template Method pattern. If you need additional help, please take a look at the full source code below, or feel free to comment, and I’ll respond directly.

Visit next week for an explanation of the Abstract Factory pattern.

View Sample Code

Leave a Reply

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