假设我写了一些这样的代码:
// 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/