Template method pattern: Difference between revisions

Content deleted Content added
PHP example: PHP-FIG PSR
Examples: use C++14 version of Design pattern book Sample Code implementation
Line 107:
 
==C++ example==
This C++14 implementation is based on the pre C++98 implementation in the book.
<syntaxhighlight lang="cpp">
#include<iostream>
 
<syntaxhighlight lang="cppc++">
// abstract
#include <iostream>
class BaseClass {
#include <memory>
protected:
 
virtual void someMethod() = 0;
class View { // AbstractClass
public:
// defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
void ThisIsTemplateMethod() { someMethod(); }
virtual void someMethoddoDisplay() = 0;{}
// implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
void display() {
setFocus();
doDisplay();
resetFocus();
}
virtual ~View() = default;
private:
void setFocus() {
std::cout << "View::setFocus\n";
}
void resetFocus() {
std::cout << "View::resetFocus\n";
}
};
 
class ExtendedClass_oneMyView : public BaseClassView { // ConcreteClass
// implements the primitive operations to carry out subclass-specific steps of the algorithm.
protected:
void someMethoddoDisplay() override {
// render the view's contents
puts("[ExtendedClass_one] Re-Define method here.");
std::cout << "MyView::doDisplay\n";
}
};
class ExtendedClass_two : public BaseClass {
protected:
void someMethod() override {
puts("[ExtendedClass_two] Re-Define method here.");
}
};
 
int main() {
// The smart pointers prevent memory leaks
std::unique_ptr<View> myview = std::make_unique<MyView>();
myview->display();
}
</syntaxhighlight>
 
The program output is
BaseClass* one = new ExtendedClass_one;
one->ThisIsTemplateMethod();
 
<syntaxhighlight lang="c++">
BaseClass* two = new ExtendedClass_two;
View::setFocus
two->ThisIsTemplateMethod();
MyView::doDisplay
 
View::resetFocus
return 0;
}
</syntaxhighlight>