定义一个操作中的算法骨架,而将一些步骤延迟到子类中
class BaseClass { public: void TemplateMethod() { Operation1(); Operation2(); } protected: virtual void Operation1() = 0; virtual void Operation2() = 0; };
class ClassA : public BaseClass { virtual void Operation1() { cout << "A1" << endl; } virtual void Operation2() { cout << "A2" << endl; } };
class ClassB : public BaseClass { virtual void Operation1() { cout << "B1" << endl; } virtual void Operation2() { cout << "B2" << endl; } };
int main() { ClassA *a = new ClassA; a->TemplateMethod(); ClassB *b = new ClassB; b->TemplateMethod(); return 0; }