从引用传递到设计模式(2)

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>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/09b7c98163127f997480678f4ba3a8dc.html