在 C++ 中使用接口进行依赖注入 [英] Using interface in C++ for dependency injection

查看:66
本文介绍了在 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
    }
};

然后在需要有接口句柄的类中(通过注入的具体类):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆