previous up next Template Method

Intent, Motivation, Applicability, Structure, Participants, Collaborations, Consequences, Implementation, Sample Code, Known Uses, Related Patterns

previous next Sample Code

The following C++ example shows how a parent class can enforce an invariant for its subclasses. The example comes from NeXT's AppKit. Consider a class View that supports drawing on the screen. View enforces the invariant that its subclasses can draw into a view only after it becomes the ``focus,'' which requires certain drawing state (for example, colors and fonts) to be set up properly.

We can use a Display template method to set up this state. View defines two concrete operations, SetFocus and ResetFocus, that set up and clean up the drawing state, respectively. View's DoDisplay hook operation performs the actual drawing. Display calls SetFocus before DoDisplay to set up the drawing state; Display calls ResetFocus afterwards to release the drawing state.

void View::Display () { SetFocus(); DoDisplay(); ResetFocus(); }
To maintain the invariant, the View's clients always call Display, and View subclasses always override DoDisplay.

DoDisplay does nothing in View:

void View::DoDisplay () { }
Subclasses override it to add their specific drawing behavior:
void MyView::DoDisplay () { // render the view's contents }


Sample Code of Abstract Factory, Adapter, Bridge, Builder, Chain of Responsibility, Command, Composite, Decorator, Facade, Factory Method, Flyweight, Interpreter, Iterator, Mediator, Memento, Observer, Prototype, Proxy, Singleton, State, Strategy, Template Method, Visitor

previous next