交换接口的实现

Swapping implementations of an interface

本文关键字:实现 接口 交换      更新时间:2023-10-16

我已经搜索了关于这个问题的讨论,包括谷歌和Stackoverflow;"实现交换"、"替换实现"等没有给我任何结果。

假设我们有一个接口DB,我目前的实现是Postgresql。现在,我想将实现换成有利于MySQL。这样做的适当方法是什么?我自己有几个想法:

  1. DB.hDB.cpp ,包含 Postgresql 实现的 cpp 文件。现在,只需将DB.cpp重命名为DB.cpp.postgresql,并将MySQL实现重命名为DB.cpp
  2. Postgresql.h / Postgresql.cppMySQL.h / MySQL.cpp,更改实际的#include<>语句。这似乎是错误的;数百个文件可以使用它,因此这会导致许多看似不必要的工作。
  3. 实现 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*/)};
  }
}

如果我没记错的话,这也称为工厂模式。