交换接口的实现
Swapping implementations of an interface
我已经搜索了关于这个问题的讨论,包括谷歌和Stackoverflow;"实现交换"、"替换实现"等没有给我任何结果。
假设我们有一个接口DB
,我目前的实现是Postgresql
。现在,我想将实现换成有利于MySQL
。这样做的适当方法是什么?我自己有几个想法:
- 有
DB.h
和DB.cpp
,包含 Postgresql 实现的 cpp 文件。现在,只需将DB.cpp
重命名为DB.cpp.postgresql
,并将MySQL实现重命名为DB.cpp
。 -
Postgresql.h / Postgresql.cpp
和MySQL.h / MySQL.cpp
,更改实际的#include<>
语句。这似乎是错误的;数百个文件可以使用它,因此这会导致许多看似不必要的工作。 - 实现 IoC 容器并从那里解析数据库驱动程序/连接器。
这三者中的任何一个是正确的,还是我们有另一种共同的方法来实现这一目标?
(警告,前面有未编译的代码)
分贝·
#include <string>
class DB
{
public:
virtual bool insert(std::string content) = 0;
// And whatever other functions your DB interface may need ...
}
MySQL.h
#include <DB.h>
class MySQL : public DB
{
public
virtual bool insert(std::string content);
}
MySQL.cpp
#include <MySQL.h>
bool MySQL::insert(std::string content)
{
// insert logic here
return true;
}
PostgreSQL也是如此。
创建数据库.cpp
#include <memory>
#include <MySQL.h>
#include <PostgreSQL.h>
enum class DBType { MySQL, PostgreSQL };
std::unique_ptr<DB> createDB(DBType type)
{
switch(type)
{
case DBType::MySQL:
return std::unique_ptr<DB>{std::make_unique<MySQL(/*constructor arguments here*/)};
case DBType::PostgreSQL:
return std::unique_ptr<DB>{std::make_unique<PostgreSQL>(/*constructor arguments here*/)};
}
}
如果我没记错的话,这也称为工厂模式。
相关文章:
- 如何从实现接口的模板化类实例访问结构
- 如何在C++中实现接口
- unique_ptr实现接口时对已删除函数的引用
- 避免对实现接口的类使用多个几乎相同的声明
- C#COM组装实现C 接口
- 当传递对类的引用时,优于另一个函数,即实现接口
- 通过其方法的子集实现接口
- C ++类实现接口,接口具有采用任何实现该接口的类的方法
- 错误:在 C++ 中实现接口模式时未定义对 typeinfo 的引用
- 与模板实现接口的类模板
- 在主应用程序中声明的 dll 中实现接口 - C++
- Objective-C类实现C 接口
- 如何添加实现C 接口的标签
- 强制接收实现接口的超类指针作为方法的参数
- 我可以部分实现接口层次结构吗
- 是否可以通过继承实现接口
- 在c++中实现接口
- 如何使用谷歌测试测试实现接口的不同类/结构
- 使用成员函数模板实现接口的功能
- C++ 11 实现接口的方法不可用。为什么?