Template methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes.
Template methods lead to an inverted control structure that's sometimes referred to as ``the Hollywood principle,'' that is, ``Don't call us, we'll call you''. This refers to how a parent class calls the operations of a subclass and not the other way around.
Template methods call the following kinds of operations:
Unfortunately, it's easy to forget to call the inherited operation. We can transform such an operation into a template method to give the parent control over how subclasses extend it. The idea is to call a hook operation from a template method in the parent class. Then subclasses can then override this hook operation:void DerivedClass::Operation () { // DerivedClass extended behavior ParentClass::Operation(); }
HookOperation does nothing in ParentClass:void ParentClass::Operation () { // ParentClass behavior HookOperation(); }
Subclasses override HookOperation to extends its behavior:void ParentClass::HookOperation () { }
void DerivedClass::HookOperation () { // derived class extension }