Template

Intent

Template Method allows subclasses to redefine steps in an algorithm without changing the structure of the algorithm. An operation defines the structure of the algorithm, subclasses can redefine individual steps

Applications

Motivation

When you have interactions between classes that can vary depending on the domain, the template method can fix the ordering of steps in an algorithm but allow the sub class to implement the domain logic in the steps

Key Objects

AbstractClass

Specifies the TemplateMethod and order of steps

Concrete Subclass

Specifies the implementation of the primitive operations

Defines the primitive operations that concrete subclasses define

Consequences

Fundamental technique for code reuse. Used in class libraries since behavior common to classes can be factored out

Inversion of Control - parent classes called child classes instead of other way around

Types of Methods Called:

Concrete Abstract Class operations - those that are useful to all subclasses

Primitive Operations - those implemented by sub classes

Concrete Operations - either abstract class or client operations

Factory methods

Hook Methods - which can be implemented by sub classes

Implementation

Use access modifiers for appropriate methods. For primitive methods use "protected", for the template method use "final" so it cannot be overriden

Minimize Primitive Operations: so subclasses do not have to implement a lot of code

Naming Conventions: Naming conventions can be used to designate methods that need to be overriden

Used in several class libraries

Related Patterns

Factory Method: Template methods often call Factory Methods

Strategy: Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.