Monday 3 August 2015

The Template Method Pattern

The Template Method Pattern



Defined

The template method defines the skeleton of an algorithm within a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changes the algorithm structure.

The Template Method Defines steps of an algorithm and allows subclasses to provided the implementation of on or more steps.

Diagrams

Code Example

example of a normal template method

 example of a template method with a hook


A hook is a method that is declared in the abstract class, but only given an empty or default implementation. This gives subclasses the ability to "hook into" the algorithm at various points, if they wish; a subclass is also free to ignore the hook.


The use the hook, we override it in our subclass.

Bullet Points

  •  The "template method" defines the steps of an algorithm, deferring to subclasses for the implementation of those steps. 
  • The Template Method Patter gives us an important technique for code re-use.
  • The Template Methods abstract class may define concrete method, abstract methods and hooks.
  •  Abstract method are implemented by subclasses.
  • Hooks are methods that do nothing or default behavior in the abstract class, but may be overridden in subclasses. 
  • To prevent subclasses from changing the algorithm in the template method, declare the template method as final. 
  • The Hollywood Principle guides use to put decisions making in high-level modules that can decide how and when to call low level modules. 
  • You'll see lots of uses of the Template Method Pattern in real world code, but don't expect it all (like any Pattern) to be designed by the book. 
  • The Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition. 
  • The Factory Method is a specialization of Template Method. 


 

No comments:

Post a Comment