Home > Patterns and Practices > Template Method

Template Method

Template Method Pattern


You have a consistent set of steps to follow but individual steps may have different implementations. For example in our project we had implemented this pattern. We had two windows services reading items (in chunks) from a queue, process each item and mark the item as processed. Thus the base algorithm for processing is same.


Messages = Read

For Each Message In Messages


            Begin Transaction

            Parse Message

                            Process Message

            Mark Message as Processed

         Commit Transaction

            Catch Exception

                        Rollback Transaction

                        Move to Failed

            End Try

Next Message


But each service had to read from different data stores.



So we implemented the above algorithm in a “template method” in the base class from the individual services derive from.


Each operation Read, Parse Message, Process Message, Mark Message As Processed, Move To Failed was an abstract method in the base class. These were implemented in the derived classes. The template method was itself a non virtual method (not overridable).


The GoF class structure diagram:


In .NET Framework,

When dealing with custom controls, there are two general types: controls that combine the functionality of several existing controls (called composite controls), and controls with a unique visual representation.

Regardless of which style of custom control you choose, you don’t have to write any code to handle the functionality that’s common to all controls, like loading and saving ViewState at the right time, allowing PostBack events to be handled, and making sure the control lifecycle events are raised in the correct order. The main algorithm for how a control should be loaded, rendered, and unloaded is contained in the control base class.

The specifics of your particular control are handled at well-defined places in the control algorithm (the CreateChildControls or Render methods). This is an example of the Template Method pattern.


As simple as that. Bye for now, rest in next 😉


  1. No comments yet.
  1. November 19, 2010 at 11:00 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: