Published: 13 Oct 2008
By: Granville Barnett
Download Sample Code

In this part of the design patterns series we will take a look at the template pattern.

Contents [hide]


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 scenario

    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 Start, Drive, and Stop methods. The Start and 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 Car.

    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 Start and Stop methods defined in the abstract Car type.

    Figure 1: Our scenario in UML form

    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

    Output of the example

    As you can see from the example the TraverseStates template method delegates the correct behavior of Start and 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.

    Providing hooks

    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 PreStart, PostStart, PreStop, and PostStop. We only need to override these methods if we need them. Certainly we might be able to exploit them in the ModelT type.

    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

    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 [1] for reviewing this article and providing a few more common examples of where the template pattern is used in real life.


    <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Granville Barnett

    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...
    TypeMock’s Arrange-Act-Assert
    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). read more
    Designing a Windows 8 Metro style app starting from an existing Windows Phone app Design Case Study Part 1 read more
    Oredev Wrap-Up read more
    Introducing SharePoint 2010 Training at U2U read more
    The Underground at PDC read more
    12 ASP.NET MVC Best Practices read more
    Screencast Whats new in the Entity Data Model Designer in VS2010 read more
    What needed to be monitored to get better Governance read more
    SharePoint 2010 Workflow read more
    Formatting Text in RadControls for WinForms Q3 2009 read more


    Subject Author Date
    placeholder minor corrections Eduard-Cristian Stefan 10/13/2008 1:41 AM
    RE: minor corrections Sonu Kapoor 10/13/2008 11:46 AM
    placeholder Right name is Template Method Simone Busoli 10/14/2008 3:15 AM
    RE: Right name is Template Method Granville Barnett 10/14/2008 6:45 AM
    placeholder RE: RE: Right name is Template Method Simone Busoli 10/14/2008 7:06 AM
    RE: RE: RE: Right name is Template Method Granville Barnett 10/14/2008 8:42 AM

    Please login to rate or to leave a comment.