PurposeDefine the calculation skeleton in an operation and delay the implementation of some steps to the subclass, the template method mode allows subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
CaseAn application framework containing the application and document classes. The application class is responsible for opening an external document. When the content in the document is read, it is represented by document. There is a method OpenDocument in the application to perform document operations:
void Application::openDocument(const char* name)
{
if(!canOpenDocument(name))
return;
Document* doc = createDocument();
if(doc != NULL)
{
m_docs->addDocument(doc);
aboutToOpenDocument(doc);
doc->open();
doc->read();
}
}
The OpenDocument of application defines every major step for opening a document. It checks whether the document can be opened and creates a Document Object related to the application, and read the document from the file. In this case, OpenDocument is
Template Method. A template method defines an algorithm with some abstract operations, and the subclass will redefine these operations to provide specific behavior:
Class application provides operations that require subclass redefinition:
class Application
{
public:
void openDocument(const char* name);
protected:
virtual void canOpenDocument(const char* name);
virtual void createDocument();
virtual void aboutToOpenDocument();
private:
vector<Document*> m_docs;
};
Myapplication requires the following operations to be customized:
class MyApplication : public Application
{
protected:
virtual Document* createDocument();
virtual void aboutToOpenDocument();
};
Document* MyApplication::createDocument()
{
return new MyDocument();
}
void aboutToOpenDocument()
{
// initialize doc object.
}
Document and mydocument are similar implementations.
Applicability
- Defines the immutable part of an algorithm at a time and leaves the variable behavior to the subclass for implementation.
- Common behaviors in each subclass should be extracted and concentrated in a common parent class to avoid code duplication.
- Control subclass extension.
Template Method-template method mode