在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);
}