Introduction to the Template Pattern

No.of Views1535
Bookmarked0 times
Downloads 
Votes0
By  Chinna Srihari   On  21 Sep 2010 01:09:05
Tag : Design Patterns , How to
In an operation that has an algorithm, define the skeleton of an algorithm by deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Definition

In an operation that has an algorithm, define the skeleton of an algorithm by deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Basically, design a base class such a way that, declare algorithm abstract methods and sequence they have to be called, and derived classes implement the placeholders.
Note:

1.    Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
2.    Strategy modifies the logic of entity objects. Template Method modifies the logic of an entire class.
3.    Factory Method is a specialized version of Template Method.

Design

Assume that we are developing hashing algorithm, to compute an algorithm we will be taking certain steps. Like first get the Bytes of the text that we need hash, then compute hash and convert it to a readable format.

UML Diagram

Image Loading

From GoF

Image Loading

Code

public abstract class TemplateAlgorithm
    {protected string _text;protected Byte[] _bytes;protected Byte[] _encodedBytes;public void TemplateMethod(string text)
        {this._text = text;this._bytes = GetBytes(_text);this._encodedBytes = ComputeHash(_bytes);
Console.WriteLine( "{0} -->  {1}",this.GetType().Name.ToString(),   GetReadableHash(_encodedBytes));
        }public abstract Byte[] GetBytes(string text);public abstract Byte[] ComputeHash(Byte[] bytes);public abstract String GetReadableHash(Byte[] encodedBytes);
    }public class MD5Algorithm : TemplateAlgorithm
    {
        MD5 _md5 = new MD5CryptoServiceProvider();public override byte[] GetBytes(string text)
        {return ASCIIEncoding.Default.GetBytes(text);
        }public override byte[] ComputeHash(Byte[] bytes)
        {return  _md5.ComputeHash(bytes);
        }public override string GetReadableHash(Byte[] encodedBytes)
        {return BitConverter.ToString(encodedBytes);
        }
    }public class SHA1Algorithm : TemplateAlgorithm
    {
        SHA1 _sha1 = new SHA1CryptoServiceProvider();public override byte[] GetBytes(string text)
        {return ASCIIEncoding.Default.GetBytes(text);
        }public override byte[] ComputeHash(Byte[] bytes)
        {return _encodedBytes = _sha1.ComputeHash(bytes);
            
        }public override string GetReadableHash(Byte[] encodedBytes)
        {return BitConverter.ToString(encodedBytes);
       }
    }

 Client

TemplateAlgorithm al = new SHA1Algorithm();
            al.TemplateMethod("Chinna");

            al = new MD5Algorithm();
         al.TemplateMethod("Chinna");

 That's all. I hope this is help to you all. Thank you for reading.

Sample Project Source

Download source files -67 kb

 
Sign Up to vote for this article
 
About Author
 
Chinna Srihari
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-17 Jun 2010
Home Page-
Blog Page-
Having 12 + years of IT experience, 2.5 years as Technical Management experience and 1.5 year of onsite coordinator experience and rest 8+ years of technical activities including Project Leader, Tech Lead, Designer, PQL, and Developer experience in Quality Management System (CMM-level 5, SEI-CMM-level 5).
 
 
Other popularSectionarticles
    The Command pattern creates distance between the client that requests an operation and the object that can perform it.
    Published Date : 20/Sep/2010
    Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
    Published Date : 22/Oct/2010
    A fully initialized instance to be copied or cloned. The Prototype pattern specifies the kind of objects to create using a prototypical instance.
    Published Date : 22/Oct/2010
    Another type of refactoring patterns is the Magic Number pattern. Magic numbers are numbers with special meaning and value that usually are not obvious, such as PI. They are really nasty when you need to reference the same number many times. If the number might ever change, making the change is a nightmare. Even if you don't make a change, you have the difficulty of figuring out what is going on.
    Published Date : 16/Feb/2010
    Design pattern – Inversion of control and Dependency injection
    Published Date : 16/Feb/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top