私有方法模式的私有覆盖? (答案:NVI)
用于描述仅虚拟调用和从基础中的其他方法调用的方法的公认术语(如果有)是什么?我偶尔会看到这被称为回调,但这似乎与该术语的原始定义相去甚远。我什至不确定这是否值得被称为模式,但我试图在注释我的代码时变得更加精确。感谢您的帮助!
// Abstract class.
class A {
public:
void run() { while (call()) { /* ... */ } }
private:
virtual bool call() = 0;
};
// Completion/specialization of A.
class B : public A {
private:
// Standard term to indicate this pattern?
bool call();
};
摘要:这似乎称为非虚拟接口模式,是模板方法模式的一种特殊情况。感谢尼克和史蒂文的帮助!
What's the accepted jargon (if any) for describing methods meant to be invoked only virtually and from other methods in the base? I've occasionally seen this referred to as a callback, but that seems to stray pretty far from the original definition of that term. I'm not even sure that this merits being called a pattern, but I'm trying to become more precise in commenting my code. Thanks for the help!
// Abstract class.
class A {
public:
void run() { while (call()) { /* ... */ } }
private:
virtual bool call() = 0;
};
// Completion/specialization of A.
class B : public A {
private:
// Standard term to indicate this pattern?
bool call();
};
Summary: This appears to be called the Non-Virtual Interface pattern, a special case of the Template Method Pattern. Thanks to Nick and Steven for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是模板方法模式。
Could be a template method pattern.
这有时称为“非虚拟接口”(或 NVI)模式。当虚函数的实现需要在派生类之间有所不同,但基类需要控制函数的调用时间时,通常会使用它。
例如,基类可以在虚拟调用之前或之后进行另一个函数调用,而不是将虚拟函数公开并依赖重写来调用基实现本身(并且在正确的时间!)
This is sometimes called the "non-virtual interface" (or NVI) pattern. It is often used when the implementation for the virtual function needs to vary between derived classes, but the base class needs control over when the function is called.
For example, the base class could make another function call before or after the virtual call instead of making the virtual function public and relying on overrides to call the base implementation themselves (and at the right time!)
我听说过这样的模式:接口中没有任何
虚拟
函数,称为非虚拟接口模式,简称为NVI。在其他上下文中,它被称为模板方法模式,其中
run()
是一个模板方法,派生类会跳进来填补空白。I've heard the pattern where you don't have any
virtual
functions in your interface as the Non-Virtual Interface pattern, NVI for short.In other contexts it's referred to as the Template Method pattern, where your
run()
is a template method, with derived classes jumping in to fill in the gaps.嗯...私人虚拟机?为什么发明新术语?这是一种语言结构,而不是一种习语,在我看来,它不够有趣,不足以被称为模式。
Um... private virtuals? Why invent new terminology? It's a language construct, not an idiom, and to my mind not interesting enough to be termed a pattern.