交换接口的实现

时间:2016-03-11 08:38:37

标签: c++

我已经四处寻找有关此问题的讨论,包括Google和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容器并从那里解析数据库驱动程序/连接器。
  4. 这三个中的任何一个是正确的,还是我们有另一种常见的方法来实现这个目标?

1 个答案:

答案 0 :(得分:3)

(警告,未编译的代码)

  

DB.h

#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。

  

createDB.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*/)};
  }
}

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