NVI手法(Non-Virtual Interface)
令客户通过public non-virtual 成员函数间接调用private virtual函数。这一手法称为 NVI手法。
代码表现如下:
class GameCharacter
{
public:
int GetHealthValue() const
{
...//做一些事前工作
int retVal = doHealthValue();//做真真的工作
...//做一些事后工作
}
private:
virtual int DoHealthValue() const
{
...
}
};
这其实也是Template Method 设计模式的一个独特表现。如果有兴趣的可以翻看我另一个专栏《设计模式》。其中将non-virtual 函数GetHealthValue()称为virtual函数的外覆器。
NVI手法的一个优点正如代码注释“做一些事前工作”和“做一些事后工作”
注意:子类可重新定义继承而来的private virutal函数
看如下例子:
class Test
{
private:
int a;
int b;
virtual int getvalue()
{
return a + b;
}
public:
Test(int x,int y)
{
a = x;
b = y;
}
int TestPriVirF()
{
return getvalue();
}
};
class Test2 :public Test
{
public:
Test2(int x, int y) :Test(x, y)
{
}
private:
virtual int getvalue() override
{
return 10;
}
};
void main()
{
Test *pT = new Test2(10,20);
cout << pT->TestPriVirF() << endl;
system("pause");
}
结果: