[英]Whats the difference between a 'non-virtual interface' and an 'abstract interface'?
I am implementing design patterns in C++ and I want my classes to utilise the interfaces via composition, this has lead me to study the different ways to implement interfaces. 我正在用C ++实现设计模式,我希望我的类通过组合来利用接口,这使我学习了实现接口的不同方法。 I would like to clarify the definitions of this terminology.
我想澄清一下这个术语的定义。
A non-virtual interface is a public member function that's not virtual, but usually expected to be implemented in terms of a virtual function which is overridable: 非虚拟接口是一个公共成员函数不是虚拟的,但一般预计是重写一个虚函数的方面来实现:
class Interface
{
public:
int compute()
{
return compute_impl();
}
private:
virtual int compute_impl() = 0;
protected:
virtual ~Interface() { }
};
The neat thing here is that the implementation is actually private
, since you can still override private methods - you just can't call them from the outside. 这里的好处是实现实际上是
private
,因为你仍然可以覆盖私有方法 - 你不能从外部调用它们。
By contrast, an abstract interface is itself virtual, and purely so in the interface class: 相比之下,抽象接口本身就是虚拟的,在接口类中完全如此:
class Interface
{
public:
virtual int compute() = 0;
protected:
virtual ~Interface() { }
};
While the two approaches look superficially similar, the advantage of the non-virtual interface idiom is that the interface is not encumbered with the implementation detail of virtual member functions. 虽然这两种方法看起来表面上相似,但非虚拟接口惯用法的优点是接口不受虚拟成员函数的实现细节的阻碍。 In other words, the fact that different implementations of the interface satisfy its contract by overriding a virtual functions is a detail of the implementation that is not part of the public aspect of the interface.
换句话说,接口的不同实现通过覆盖虚函数来满足其契约的事实是实现的细节,其不是接口的公共方面的一部分。 In particular, the author is free to change the way the function is implemented in the future without having to worry about users having developed their own inheritance and override hierarchies.
特别是,作者可以自由地改变将来实现该函数的方式,而不必担心用户已经开发了自己的继承并覆盖了层次结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.