Junior — Middle
Can you explain what it means to create an instance using the template method?
sobes.tech AI
Answer from AI
Creating an instance using the Template Method pattern is a design pattern that defines the skeleton of an algorithm in a base class, while the specific steps of the algorithm are implemented in subclasses.
That is, the base class contains a method that sets the sequence of calls to other methods (the template), some of which can be abstract or virtual so that subclasses can override them.
Example in C++:
#include <iostream>
class AbstractClass {
public:
void TemplateMethod() {
Step1();
Step2();
Step3();
}
protected:
void Step1() { std::cout << "General step 1\n"; }
virtual void Step2() = 0; // Step to be implemented by subclass
void Step3() { std::cout << "General step 3\n"; }
};
class ConcreteClass : public AbstractClass {
protected:
void Step2() override {
std::cout << "Concrete implementation of step 2\n";
}
};
int main() {
ConcreteClass obj;
obj.TemplateMethod();
return 0;
}
In this example, TemplateMethod sets the order of calling steps, and the specific step Step2 is implemented in the subclass. This allows reusing the algorithm structure and changing details in subclasses.