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:
Post a Comment