Applied Design Patterns with Java

Behavioral :: Template Method (325) {C ch 25}

Implementation

The following three implementation issues are relevant to the Template Method pattern:

  1. Using access control labels. In Java, the primitive operations that a Template Method calls can be declared protected members. This ensures that they are only called by the Template Method. Primitive operations that must be overridden are declared abstract. The template method itself should not be overridden; thus, the Template Method can be a nonvirtual member function.
  2. Minimizing primitive operations. An important goal in designing Template Methods is to minimize the number of primitive operations that a subclass must override to flesh out the algorithm. The more operations that need overriding, the more tedious things get for clients.
  3. Naming conventions. Identify the operations that should be overridden by adding a prefix to their names. For example, the MacApp framework for Macintosh applications prefixes Template Method names with "Do-": "DoCreateDocument", "DoRead", and so forth.

Related Patterns

Factory Methods (107) are often called by Template Methods. In the Motivation example, the Factory Method DoCreateDocument is called by the Template Method OpenDocument.

Strategy (315): Template Methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.

Catalog Behavioral Prev Next