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.
To maintain the invariant, the View's clients always call Display, and View subclasses always override DoDisplay.void View::Display () { SetFocus(); DoDisplay(); ResetFocus(); }
DoDisplay does nothing in View:
Subclasses override it to add their specific drawing behavior:void View::DoDisplay () { }
void MyView::DoDisplay () { // render the view's contents }