使用C ++接口的最佳方式 [英] Best way to use a C++ Interface
问题描述
我的接口类类似于:
class IInterface
{
public:
virtual ~IInterface() {}
virtual methodA() = 0;
virtual methodB() = 0;
};
然后我实现了界面:
class AImplementation : public IInterface
{
// etc... implementation here
}
当我在应用程序中使用接口时,最好创建具体类AImplementation的实例。例如。
When I use the interface in an application is it better to create an instance of the concrete class AImplementation. Eg.
int main()
{
AImplementation* ai = new AIImplementation();
}
或者在接口中放置工厂创建成员函数更好如下所示:
Or is it better to put a factory "create" member function in the Interface like the following:
class IInterface
{
public:
virtual ~IInterface() {}
static std::tr1::shared_ptr<IInterface> create(); // implementation in .cpp
virtual methodA() = 0;
virtual methodB() = 0;
};
然后我就可以在main中使用这样的接口:
Then I would be able to use the interface in main like so:
int main()
{
std::tr1::shared_ptr<IInterface> test(IInterface::create());
}
第一种选择似乎是常见做法(不是说它的权利)。但是,第二个选项来自Effective C ++。
The 1st option seems to be common practice (not to say its right). However, the 2nd option was sourced from "Effective C++".
推荐答案
使用界面的最常见原因之一是你可以编写一个抽象的程序而不是具体的实现。
One of the most common reasons for using an interface is so that you can "program against an abstraction" rather then a concrete implementation.
这样做的最大好处是它允许更改代码的各个部分,同时最大限度地减少剩余代码的更改。
The biggest benefit of this is that it allows changing of parts of your code while minimising the change on the remaining code.
因此,虽然我们不知道您正在构建的完整背景,但我会选择接口/工厂方法。
Therefore although we don't know the full background of what you're building, I would go for the Interface / factory approach.
话虽如此,在较小的应用程序或原型中,我经常从具体的类开始,直到我感觉到界面在哪里/是否需要。接口可以引入一个间接级别,这对于您正在构建的应用程序规模可能不是必需的。
Having said this, in smaller applications or prototypes I often start with concrete classes until I get a feel for where/if an interface would be desirable. Interfaces can introduce a level of indirection that may just not be necessary for the scale of app you're building.
由于较小的应用程序,我发现我实际上并不需要自己的自定义界面。像许多事情一样,你需要权衡特定于你的情况的成本和收益。
As a result in smaller apps, I find I don't actually need my own custom interfaces. Like so many things, you need to weigh up the costs and benefits specific to your situation.
这篇关于使用C ++接口的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!