1.Topics‎ > ‎Architecture‎ > ‎Patterns‎ > ‎a.Design Patterns‎ > ‎D.Behavioral Patterns‎ > ‎

Template Method Pattern

  1. Summary
    1. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
    2. Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure.
  2. When to Use
    1. When you need to write generic implementation that need to be work with any type or multiple types.
  3. Example 
    1. Generic shorting mechanism provided by .net  collections.
  4. Overview Tutorials 
    1. http://www.oodesign.com/template-method-pattern.html
  5. Specific Considerations
    1. Concrete base class
      1. It is not necessary to have the superclass as a abstract class. It can be a concrete class containing a method (template method) and some default functionality.
      2. In this case the primitive methods can not be abstract and this is a flaw because it is not so clear which methods have to be overridden and which not.
      3. A concrete base class should be used only when customizations hooks are implemented.
    2. Template method can not be overridden
      1. The template method implemented by the base class should not be overridden. 
      2. The specific programming language modifiers should be used to ensure this.
    3. Minimizing primitive methods number
      1. It's important when designing template methods to minimize the number of primitive methods that a subclass must override in order to provide a clear an easy way to implement concrete templates.
    4. Naming Convection
      1. In order to identify the primitive methods is it better to use a specific naming convention. For example the prefix “do” can be used for primitive methods. 
      2. In a similar way the customizations hooks can have prefixes like “pre” and “post”. 
    5. Template Method Vs Strategy Design Pattern 
      1. The strategy and Template Method pattern both achieve same goal with different approaches.
      2. The difference consists in the fact that Strategy uses delegation while the Template Methods uses the inheritance.
    6. Template Method and Inverted Control Structure (Hollywood principle) 
      1. Template method is using as an inverted controls structure, sometimes referred as “the Hollywood principle”: from the superclass point of view: “Don't call us, we'll call you” (base will not call derived but derived will call base).
      2.  This refers to the fact that instead of calling the methods from base class in the subclasses, the methods from subclass are called in the template method from superclass.
      3.  Due to the above fact a special care should be paid to the access modifiers: the template method should be implemented only in the base class, and the primitive method should be implemented in the subclasses.
    7. Templates Hooks
      1. A particular case of the template method is represented by the customization hooks.