class AbstractClass {
public:
...
void TemplateMethod();
protected:
virtual void PrimitiveOperation1() = 0;
virtual void PrimitiveOperation2() = 0;
};
class ConcreteClass : public AbstractClass {
...
protected:
void PrimitiveOperation1() override;
void PrimitiveOperation2() override;
};
void AbstractClass::TemplateMethod()
{
PrimitiveOperation1();
PrimitiveOperation2();
}
由上面的例子可以看到,模板方法是关于基类如何调用派生类内操作函数的,是一种反向控制结构,常用于代码复用。
这种反向结构也体现了一个设计原则,即好莱坞原则 — “不要给我们打电话,我们会打给你”
小结:
1) use pass-by-value for small objects;use pass-by-const-reference to pass large values that you don’t need to modify
2) dynamic binding happens when a virtual function is called through a reference (or a pointer) to a base class
3) Tempalte method pattern - define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
4) Hollywood principle - don't call us, we'll call you
参考资料:
<C++ Programming Language_4th> ch 12.2.1
<Effective C++_3rd> item 20
<C++ Primer_5th> ch 6.2, ch 15.1
<Design Patterns>