Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Template Method

An application framework allows you to inherit from a class or set of classes and create a new application, reusing most of the code in the existing classes and overriding one or more functions in order to customize the application to your needs. A fundamental concept in the application framework is the Template Method, which is typically hidden beneath the covers and drives the application by calling the various functions in the base class (some of which you have overridden in order to create the application).

An important characteristic of the Template Method is that it is defined in the base class (sometimes as a private member function) and cannot be changed the Template Method is the thing that stays the same. It calls other base-class functions (the ones you override) in order to do its job, but the client programmer isn t necessarily able to call it directly, as you can see here:

//: C10:TemplateMethod.cpp
// Simple demonstration of Template Method.
#include <iostream>
using namespace std;
 
class ApplicationFramework {
protected:
virtual void customize1() = 0;
virtual void customize2() = 0;
public:
void templateMethod() {
for(int i = 0; i < 5; i++) {
customize1();
customize2();
}
}
};
 
// Create a new "application":
class MyApp : public ApplicationFramework {
protected:
void customize1() { cout << "Hello "; }
void customize2() { cout << "World!" << endl; }
};
 
int main() {
MyApp app;
app.templateMethod();
} ///:~
 

The engine that runs the application is the Template Method. In a GUI application, this engine would be the main event loop. The client programmer simply provides definitions for customize1( ) and customize2( ) and the application is ready to run.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire