The Template Pattern is Cool Reply

2_bgI find when reviewing code to solve a relatively mundane process with several procedural steps that no pattern is used. The code becomes difficult to support and the intent of the process is muddied by the lack of design. Usually due to two leading factors.  The first factor is lack of experience in the developer – create one class and a few methods with no pattern  and you got it – right? Wrong. This coding style throws your fellow developers to the wolves.

More commonly is the lack of time for proper analysis because it has to be done yesterday (<<Insert panic reason from management here>>). Maintenance and changes are inevitable and after a while the code becomes the familiar “Spaghetti code” that most developers want to run from. I found myself revisiting the trusty Gang of Four Design Patterns  just to see if my travels could have been better guided by any one of the patterns.  The answer is yes.

The Template Pattern stands out. It helps with the scenario above and it  is simple!

The template patterns definition is: Define the skeleton of a process in an operation – defer those steps to some sub classes.  The Template Method allows sub classes to redefine the steps used by the process without changing the operations structure.  Here is a sample console app I created to gel the concept. Here is the project structure:

proj

Classes explained below:

Program.cs –  the launcher for the the other classes.

//To make use of the pattern simply make the following calls:
class Program
{
    public static void Main(string[] args)
    {
         AbstractClass aA = new ConcreteClassA();
           aA.TemplateMethod();
 
          AbstractClass aB = new ConcreteClassB();
          aB.TemplateMethod();
 
  // Wait for user
  Console.ReadKey();
        
        
    }
}

AbstractClass.cs – Is an abstract class the defines the steps of an operation to be called in some sequence.

abstract class AbstractClass
{
    public abstract void PrimitiveOperation1();
    public abstract void PrimitiveOperation2();
    public abstract void  Multiply();
    // The "Template method"
    public void TemplateMethod()
    {
      PrimitiveOperation1();
      PrimitiveOperation2();
      Multiply();
      Console.WriteLine("");
    }
}

ConcreteClassA.cs – class that inherits “Abstract Class” and overrides the steps defined providing its own implementation of each step defined in ‘Abstract Class”.

//This class inherits “AbstractClass” and 
//overrides each of it’s methods changing the implementation but not the process. 
class ConcreteClassA : AbstractClass 
{
       public override void Operation1()
        {
          Console.WriteLine("ConcreteClassA.Operation1()");
        }
        public override void Operation2()
        {
          Console.WriteLine("ConcreteClassA.Operation2()");
        }
        
        public override void Multiply()
        {
            string x = "43";
            string y = "546";
            int result = (int.Parse(x) * int.Parse(y));
            Console.WriteLine(string.Format(
"Multiply Operation:{0} x {1} = {2}",x,y,result.ToString()));
        }
}

ConcreteClassB.cs – The same as above but with different implementation.

//Again inherits “AbstractClass” and 
//overrides each of it’s methods changing the implementation but not the process.
class ConcreteClassB : AbstractClass
    {
        
             public override void Operation1()
            {
              Console.WriteLine("ConcreteClassB.Operation1()");
            }
            public override void Operation2()
            {
              Console.WriteLine("ConcreteClassB.Operation2()");
            }
            
            public override void Multiply()
            {
                
            Console.WriteLine("Not Implemented..");
            }
        
    }

This pattern is great because the intent of the process is clearly defined in a sequence in one class. But, with many versions of the same process.

I can see this pattern in use in the export to Excel game, or client based processes for example.  Imagine a template method named “Export to Excel” which defines a sequence of methods.  The steps are implemented by an ExcelExporter subclass which implements, DBConnect(),  GetData(), BuildExceleDoc(), SendToClient(), Dispose().   What if the SendToClient() method requires both delivery by e-mail or HTTP download?   This pattern implementations could be messy but it can maybe provide a method to the madness.

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