我已经搜索了关于这个问题的讨论,包括谷歌和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*/)};
}
}
如果我没记错的话,这也称为工厂模式。