Saturday, November 13, 2010

..........Template Pattern

The Template Design Pattern is perhaps one of the most widely used and useful design pattern. It is used to set up the outline or skeleton of an algorithm, leaving the details to specific implementations later. This way, subclasses can override parts of the algorithm without changing its overall structure.
This is particularly useful for separating the variant and the invariant behaviour, minimizing the amount of code to be written. The invariant behaviour is placed in the abstract class (template) and then any subclasses that inherit it can override the abstract methods and implement the specifics needed in that context. In the body of TemplateMethod() there are calls to operation1() and operation2(). What it is that operation1() and operation2() do are defined by the subclasses which override them.


public static void main()
{
TemplateClass aA = new ClassA();
aA.TemplateMethod();

TemplateClass aB = new ClassB();
aB.TemplateMethod();

// Wait for user
Console.ReadKey();
}


///
/// The 'TemplateClass' abstract class
///

abstract class TemplateClass
{
public abstract void Method1();
public abstract void Method2();

// The "Template method"
public void TemplateMethod()
{
Method1();
Method2();
}
}

///
///
///

class ClassA: TemplateClass
{
public override void Method1()
{
Console.WriteLine("Method1 in ClassA");
}
public override void Method2()
{
Console.WriteLine("Method2 in ClassA);
}
}

///
///
///

class ClassB : TemplateClass
{
public override void Method1()
{
Console.WriteLine("Method1 in ClassB");
}
public override void Method2()
{
Console.WriteLine("Method2 in ClassB");
}
}

No comments:

Followers

Link