在C ++中使用接口进行依赖注入 [英] Using interface in C++ for dependency injection
本文介绍了在C ++中使用接口进行依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下抽象类并将其用作C ++中的接口:
Assume I have the following abstract class and use it as an "interface" in C++:
class IDemo
{
public:
virtual ~IDemo() {}
virtual void Start() = 0;
};
class MyDemo : IDemo
{
public:
virtual void start()
{
//do stuff
}
};
然后在需要有接口句柄的类中(通过注入具体类): / p>
Then in the class that need to have a handle to the interface (concrete class through injection):
class Project
{
public:
Project(IDemo demo);
private:
IDemo *_demo;
};
我的目的是通过Project的构造函数分配具体的Demo类。此代码无法编译,因为IDemo无法实例化。有什么建议么?
提前致谢。
My intention is to assign concrete Demo class through the constructor of Project. This code doesn't compile since IDemo can't be instantiated. Any suggestions? Thanks in advance.
推荐答案
尝试:
Project::Project(IDemo* demo)
: _demo(demo)
{}
但是如果演示对象在项目的生命周期内永远不会改变,那么我更愿意通过引用传递:
But If the demo object is never going to change for the lifetime of the project then I prefer to pass by reference:
class Project
{
public:
Project(IDemo& d)
: demo(d)
{}
private:
IDemo& demo;
};
然后像这样使用它:
int main()
{
MyDemo demo;
Project project(demo);
}
这篇关于在C ++中使用接口进行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文