c++ - 如何在不更改代码的情况下替换接口(interface)的实现?

标签 c++ interface

假设我写了一些这样的代码:

// myinterface.h
struct MyInterface { void foo()=0; };

// mydefault.h
#include "myinterface.h"
struct MyDefaultImplementation : MyInterface { void foo(){} };

// main.cpp
#include "myinterface.h"
#include "mydefault.h"    // (X)
int main(){
    MyInterface* x = new MyDefaultImplementation();  // (X)
    x->foo();
}

我可以轻松地提供接口(interface)的不同实现,但我需要更改创建实例的行,当然还有 include (X)。

是否可以在不更改现有代码的情况下替换接口(interface)的实现?

澄清一下:当然,使用上面的代码是不可能的,但是我能以某种方式更改它吗,这样以后当我想切换到接口(interface)的另一个实现时就不必更改它了?

我能找到的最接近的是 this , 但那是 java :(

顺便说一句,这个例子非常简单,但在我的实际代码中,代码中只有一行,我在其中创建了实例。

最佳答案

使用工厂方法,例如:

我的接口(interface).h

struct MyInterface
{
    virtual ~MyInterface() {}
    virtual void foo() = 0;
};

MyInterface* createMyInterface();

主要.cpp

#include "myinterface.h"

int main()
{
    MyInterface* x = createMyInterface();
    x->foo();
    delete x;
}

然后你可以让 createMyInterface() 创建你需要的任何结构类型,例如:

我的默认.h

#include "myinterface.h"

struct MyDefaultImplementation : MyInterface
{
    void foo(){}
};

我的界面.cpp

#include "mydefault.h"

MyInterface* createMyInterface()
{
    return new MyDefaultImplementation;
}

关于c++ - 如何在不更改代码的情况下替换接口(interface)的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319324/

相关文章:

interface - 通过引用设置接口(interface){}参数

delphi - 在Delphi中使用接口(interface)有哪些优点和缺点?

c++ - 为什么我们在 C++ 中需要 `class`?

c++ - AVFrame buf 大小计算

c++ - 返回使用自定义分配器的 vector

android-fragments - 当您想在 android studio 3.6.3 中创建新片段时,复选框 "include interface callbacks"在哪里

java - Dagger 2 模块 "interfaces"?

java - Rhino:在 Javascript 实现中访问 Java 接口(interface)变量

c++ - 为什么在前向声明后出现未定义类型错误?

c++ - DLL 中使用的全局变量