Home
Manage Your Code
Snippet: Template Pattern (C#)
Title: Template Pattern Language: C#
Description: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Views: 440
Author: Michael Gage Date Added: 3/1/2007
Copy Code  
1  abstract class AbstractClass
2  {
3    public abstract void PrimitiveOperation1();
4    public abstract void PrimitiveOperation2();
5
6    // The "Template method" 
7    public void TemplateMethod()
8    {
9      PrimitiveOperation1();
10      PrimitiveOperation2();
11      Console.WriteLine("");
12    }
13  }
Usage
  // "ConcreteClass" 

  class ConcreteClassA : AbstractClass
  {
    public override void PrimitiveOperation1()
    {
      Console.WriteLine("ConcreteClassA.PrimitiveOperation1()");
    }
    public override void PrimitiveOperation2()
    {
      Console.WriteLine("ConcreteClassA.PrimitiveOperation2()");
    }
  }
Notes
This structural code demonstrates the Template method which provides a skeleton calling sequence of methods. One or more steps can be deferred to subclasses which implement these steps without changing the overall calling sequence.