Total votes: 1
Category: Design Patterns
Print: Print Article
Please login to rate or to leave a comment.
Published: 13 Oct 2008
Download Sample Code
In this part of the design patterns series we will take a look at the template pattern.
With the name template pattern you might be misdirected towards thinking that this pattern is some way connected to template based programming (C++) or generics (Java, C#). The assumption would be incorrect; however, you would be forgiven for making such an assumption based on name alone.
The template pattern revolves around the encapsulation of an algorithm, of which bits of the algorithm are delegated to its subclasses. This definition is by no means thorough but it will give you a sense of what the template pattern is about.
The template pattern
Like we mentioned earlier the template pattern is all about encapsulating an algorithm and allowing subclasses, when required, the ability to define the behavior of specific steps of the algorithm itself. Each step of the algorithm is represented as a method call. The methods themselves that make the sum total of the algorithm are encapsulated within a method. This encapsulating method is known as the template method.
The template method is closed to modification. Generally the template method will live in an abstract class. The methods that the template delegates to its subclasses are also abstract, however, the template method isn’t.
Now that we have discussed the template pattern briefly lets apply it to a simple scenario to make it clearer.
Design Patterns Series
Part 1 Learn how to design more robust and maintainable code by incorporating design patterns into your software projects.
Part 2 This part shows the observer design pattern.
Part 3 In this part you will learn about the factory pattern.
Part 4 This part of the design patterns covers the singleton pattern.
Part 5 In this part of the design patterns series we investigate the command pattern and its uses.
Part 6 In this part of the design patterns series we will look at the adapter pattern.
Part 7 In this part of the design patterns series we will take a look at the template pattern.
The example that we will use will revolve around cars once more. The algorithm being encapsulated will simulate the transition of three operational states of a car – on, running, and off. All cars do the same thing when they are running (well they do in this example), that is they move in a direction. Although in the present day most cars are started via a key based ignition in the old days some poor old fellow would have to crank the engine first. Similarly cars today are easily turned off whereas in the old days you may have needed to do something a little different.
Our template method will make sequential calls to the
Stop methods. The
Stop methods will delegate to the subclass for the correct behavior and we will assume that the running of all cars is the same. We will call the template method
TraverseStates. Even though the method name implies it, rest assured that we aren’t doing any state based work, but as we are transitioning through the three car states it seems a decent name to use. All of the aforementioned methods will live in an abstract class named
Now that we have a little context lets go ahead and define a few
Car types. Let’s have a
ModelT type that represents a Model T Ford, a
Vanquish that is an Aston Martin, and finally a
Focus made by Ford once more.
Each of the derived
Car types will have to provide implementations for the
Stop methods defined in the abstract
Figure 1: Our scenario in UML form
The following code is the implementation of our design.
Listing 1: Car.cs
Listing 2: ModelT.cs
Listing 3: Vanquish.cs
Listing 4: Focus.cs
If you build and run the solution you will be graced with the following output.
Figure 2: Output of the example
As you can see from the example the
TraverseStates template method delegates the correct behavior of
Stop to the appropriate subclass. In our example the chunks that make up the
TraverseStates method are very simple; however this pattern lends itself particularly well to much more complex scenarios.
Often in the template pattern you will come across a method called within the template method whose definition comprises of an empty body, or a very small one that exhibits core default behavior. This method doesn’t have to be implemented by subclasses but they can if they want to. Such a method is known as a hook. In C# 3.0 it is also possible to provide such hooks without subclassing by using partial methods.
Let’s add to our
Car type four hooks –
PostStop. We only need to override these methods if we need them. Certainly we might be able to exploit them in the
Listing 5: Car.cs
Listing 6: ModelT.cs
Listing 7: Program.cs
If you build and run the project you will see the following output.
Figure 3: Output of the example
Notice that only the
ModelT type takes advantage of the hooks defined in the
Car type. It is up to each car whether or not they want to partake in the invocation of any of the hooks on offer.
Examples of the template pattern
The template pattern is used in a wide array of places from the page event lifecycle in ASP.NET, to a similar sort of lifecycle exposed by Windows Forms and WPF. Not only is it present within GUI libraries it is also prevalent in not so obvious ways. For example, when you use a sorting algorithm it relies upon the type of collection it is sorting to provide some method to determine the natural order of that respective type. Although this doesn’t use inheritance it does delegate the implementation of the actual comparer method to a concrete type. Another common example is where resource management is conducted within a sealed method and the abstract method is passed that resource. Such an approach relieves implementers of the abstract method from worrying about resource management.
We looked briefly at hooks earlier on. The ASP.NET page event lifecycle is a good example of providing many hooks that the user can go ahead and tap into but only if they want to. Hooks provide a way to give users more freedom in how they affect the algorithm encapsulated within the template method.
In this part of the design patterns series we looked at the template pattern. The template pattern encapsulates an algorithm and exposes an arbitrary number of steps within the algorithm that subclasses can define the behavior of. The template method delegates the behavior of these steps to the appropriate subclass. While the steps delegated to the subclasses are required to be implemented, hooks are not. Hooks provide an opt-in way of giving the user more freedom to affect the algorithm.
I would like to thank Jon Skeet  for reviewing this article and providing a few more common examples of where the template pattern is used in real life.
Sorry, no bio is available
This author has published 32 articles on DotNetSlackers. View other articles or the complete profile here.
Other articles in this category
Introduction to StructureMap
Have you heard of StructureMap, generally know what it’s for, and want to know how to get started qu...
DI Patterns: Constructor Injection
In this article, an excerpt from the book "Dependency Injection in .NET", we will take a detailed lo...
The Command Pattern
In this article I will provide a quick refresher on what the command pattern is used for, how it wor...
Brian Mains discusses how to implement the Arrange-Act-Assert pattern in TypeMock.
Key Process Patterns
This article, based on chapter 2 of Specification by Example, presents effective patterns for softwa...
You might also be interested in the following related blog posts
Learn design patterns from real projects: JBoss case study (Part 1).
Designing a Windows 8 Metro style app starting from an existing Windows Phone app Design Case Study Part 1
Introducing SharePoint 2010 Training at U2U
The Underground at PDC
12 ASP.NET MVC Best Practices
Screencast Whats new in the Entity Data Model Designer in VS2010
What needed to be monitored to get better Governance
SharePoint 2010 Workflow
Formatting Text in RadControls for WinForms Q3 2009
Please login to rate or to leave a comment.