条款35:考虑 virtual 函数以外的其他选择

Consider alternatives to virtual functions.

在为解决问题寻找某个设计方法时,不妨考虑 virtual 函数的替代方案:

  • 使用 non-virtual interface(NVI);

  • 将 virtual 函数替换为 ”函数指针的成员变量”;

  • 以 tr1::function 成员变量替换 virtual 函数;

  • 将继承体系内的 virtual 函数替换为另一个继承体系内的 virtual 函数;

藉由 Non-Virtual Interface 手法实现 Template Method 模式

class GameCharacter {
public:
    int healthValue() const {
        ...
        int retVal = doHealthValue();
        ...
        return retVal;
    }
private:
    virtual int doHealthValue() const { ... }
};

通过 public non-virtual 成员函数间接调用 private virtual 函数的方法称为 non-virtual interface(NVI)手法,而这个 non-virtual 函数称为 virtual 函数的外覆器(wrapper)。外覆器可以保证在一个 virtual 函数被调用之前设定好适当场景,并在调用结束之后清理场景。

  • 事前工作:锁定互斥锁(locking a mutex)、制造运转日志记录项(log entry)、验证 class 约束条件、验证函数先决条件等等;

  • 事后工作:互斥器解除锁定(unlocking a mutex)、验证函数的事后条件、再次验证 class 约束条件等等;

”重新定义 virtual 函数“表示某些事”如何“被完成,”调用 virtual 函数“表示它”何时“被完成。NVI 手法允许 derived classes 重新定义 virtual 函数,从而赋予它们”如何实现机能“的控制能力,但 base class 保留诉说”函数何时被调用“的权利。

藉由 Function Pointers 实现 Strategy 模式

通过函数指针的方式实现运行时的多态:

class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);

class GameCharacter {
public:
    typedef int (*HealthCalcFunc)(const GameCharacter&);
    explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc): healthFunc(hcf) {}
    int healthVal() const {
        return healthFunc(*this);
    }
private:
    HealthCalcFunc healthFunc;
};

这种实现方式有两种弹性特性:

  • 同一个class 的不同实例可以有不同的计算函数;

  • 同一个实例的计算函数可随程序运行而改变;

藉由 tr1::function 完成 Strategy 模式

基于函数指针的做法比较死板,因为它:

  • 要求实现必须是一个函数,而不能是某种”像函数的东西(例如函数对象)“;

  • 要求函数不能是某个成员函数,不能是返回类型不同但可以被隐式转换的函数;

所以当客户需求更加弹性时,可以使用 tr1::function,它可持有任何可调用物(callable entity,即函数指针

函数对象或成员函数指针),只要其签名式兼容即可:

class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);

class GameCharacter {
public:
    typedef std::tr1::function<int (const GameCharacter&)> HealthCalcFunc;
    explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc): healthFunc(hcf) {}
    int healthVal() const {
        return healthFunc(*this);
    }
private:
    HealthCalcFunc healthFunc;
};

其中 int (const GameCharacter&) 为目标签名式,即”接受一个 reference 指向 const GameCharacter 的参数,并返回 int“的调用物。而 tr1::function 相当于一个指向函数的泛化指针:

short calcHealth(const GameCharacter&);            // 计算函数,返回类型为 short

struct HealthCalculator {
    int operator()(const GameCharacter&) const {}  // 函数对象
};

class GameLevel {
public:
    float health(const GameCharacter&) const;      // 成员函数,返回为 float
};

GameCharacter g1(calcHealth);                      // 使用函数计算
GameCharacter g2(HealthCalculator());

GameLevel currentLevel;
GameCharacter g3(
    std::tr1::bind(&GameLevel::health, currentLevel, _1)
    );

GameLevel::health 宣称它接受一个参数,但实际上是两个,因为第一个参数是隐式参数 *this ,而 GameCharacter 要求的计算函数只接受单一参数。所以 currentLevel 即作为默认的 *this 值,而 tr1::bind 的作用指明这个关系。

古典的 Strategy 模式

传统的 Strategy 做法会将原 virtual 函数做成一个分离的继承体系中的 virtual 成员函数。

Last updated

Was this helpful?