diff --git a/template-method/README.txt b/template-method/README.txt new file mode 100644 index 0000000..05c2ed5 --- /dev/null +++ b/template-method/README.txt @@ -0,0 +1,12 @@ +## Template Method + +Template method defines the skeleton of an algorithm in an operation, deferring some +steps to subclasses. It lets subclasses redefine certain steps of an algorithm +without changing the algorithm's structure. The pattern has behavioral purpose and +applies to the classes. + +### When to use + +* to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary +* when common behavior among subclasses should be factored and localizedin a common class to avoid code duplication +* to control subclasses extensions \ No newline at end of file diff --git a/template-method/TemplateMethod.cpp b/template-method/TemplateMethod.cpp new file mode 100644 index 0000000..4a9c6ae --- /dev/null +++ b/template-method/TemplateMethod.cpp @@ -0,0 +1,59 @@ +/* + * C++ Design Patterns: Template Method + * Author: Jakub Vojvoda [github.com/JakubVojvoda] + * 2016 + * + * Source code is licensed under MIT License + * (for more details see LICENSE) + * + */ + +#include + +/* + * AbstractClass + * implements a template method defining the skeleton of an algorithm + */ +class AbstractClass { +public: + void templateMethod() { + // ... + primitiveOperation1(); + // ... + primitiveOperation2(); + // ... + } + + virtual void primitiveOperation1() = 0; + virtual void primitiveOperation2() = 0; + // ... +}; + +/* + * Concrete Class + * implements the primitive operations to carry out specific steps + * of the algorithm, there may be many Concrete classes, each implementing + * the full set of the required operation + */ +class ConcreteClass : public AbstractClass { +public: + void primitiveOperation1() { + std::cout << "Primitive operation 1" << std::endl; + // ... + } + + void primitiveOperation2() { + std::cout << "Primitive operation 2" << std::endl; + // ... + } + // ... +}; + + +int main() +{ + AbstractClass *tm = new ConcreteClass; + tm->templateMethod(); + + return 0; +}