Design Patterns - Template Method Pattern

Time for yet another pattern, the Template Method Pattern. Have a look at all the other patterns in the series as well.

The definition: "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure."

Let's add an additional requirement to our game. We need different types of renderers for our GUI, the main screen is in 3D, while the map is displayed in 2D. Both layouts follow a specific drawing order. First the background, then the units, on screen instructions, special effects and a border. If this order is wrong, it would be possible for the background to overlap the units, which we don't want.

We'll start by creating a new base class for our renderers, with some abstract methods which make up the algorithm of drawing the screen.

Base Class

As you can see, there are two non-abstract methods. DrawBorder() which is common functionality for every render and RenderScreen() which is actually a Template Method.

The Template Method defines the steps used in the algorithm, without actually implementing the steps itself.

Template Method

As you can see from the comments, with the perfect implementation, RenderScreen() should be a method which can't be overridden by child classes. C# doesn't support this however.

When we create our two renderers and have the discipline to not hide RenderScreen(), the class diagram for the Template Method Pattern looks like this:

Class Diagram Template Method Pattern

If we test this code, we notice that the order of rendering a screen is the same, but that each engine implements the steps differently, or not at all.

Testing Template Method Pattern

And that's the Template Method Pattern! I've uploaded the solution again to have a look at.

Some additional information on the Template Method Pattern: