Is dependency injection useful in C++

前端 未结 5 1465
暗喜
暗喜 2021-01-31 02:39

C# uses Dependency Injection (DI) a lot to have a lossless and testable platform. For this, I need

5条回答
  •  花落未央
    2021-01-31 03:31

    Using dependency injection is quite straightforward in C++. Just define an interface (a pure abstract base class) that you use as reference or pointer (or smart pointer) argument to the constructor or init function of the class you want to dependency inject into.

    Then, in the unit test, inject a mock object (an instance of a class inheriting from the abstract interface class), and in real code, inject an instance of the real class (also inheriting from the same interface class).

    Easy-peasy.

提交回复
热议问题