DefinitionIn 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. DesignAssume 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 DiagramFrom GoFCode 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 SourceDownload source files -67 kb |