Template Method Design Pattern

 definition
 UML diagram
 participants
 sample code in C#



definition

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.

Frequency of use:   medium

UML class diagram


participants

    The classes and/or objects participating in this pattern are:

  • AbstractClass  (DataObject)
    • defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm
    • implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
  • ConcreteClass  (CustomerDataObject)
    • implements the primitive operations ot carry out subclass-specific steps of the algorithm

sample code in C#

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.

Show code

// Template Method pattern -- Structural example




This real-world code demonstrates a Template method named Run() which provides a skeleton calling sequence of methods. Implementation of these steps are deferred to the CustomerDataObject subclass which implements the Connect, Select, Process, and Disconnect methods.

Show code

// Template Method pattern -- Real World example




This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// Template Method pattern -- .NET optimized




Need to know more?

    see what others are saying about the Template Method pattern



  • Better Code
  • Better Career
  • Better Lifestyle


Design Pattern
FrameworkTM 4.0


 
C# and VB.NET


     Here's what you get:
  • Gang of Four Patterns
  • Head First Patterns
  • Enterprise Patterns
  • SOA Patterns

  • WPF Best Practices
  • WCF Best Practices
  • LINQ Best Practices

  • Model View Controller
  • Model View Presenter
  • Model View ViewModel

  • More...

Click here for details

-- Instant Access --
Instant Download