动机:
数据库demo:
版本1:
EmployeeDAO.cpp
class EmployeeDAO{
public:
vector<EmployeeDO> GetEmployees(){
SqlConnection* connection = new SqlConnection();
connection->ConnectionString("...");
SqlCommand* command = new SqlCommand();
command->CommandText("...");
SqlDataReader* reader = command->ExecuteReader();
while(reader->Read()){
}
}
};
版本2:
EmployeeDAO2.cpp
//数据库访问有关的基类
class IDBConnection{
};
//工厂基类
class IDBConnectionFactory{
public:
virtual IDBConnection* CreateDBConnection() = 0;
};
class IDBCommand{
};
class IDataReader{
};
//支持Sql server
class SqlConnection : public IDBConnection{
};
//具体工厂
class SqlConnectionFactory : public IDBConntionFactory{
};
class SqlCommand : public IDBCommand{
};
class SqlDataReader : public IDataReader{
};
//支持Oracle
class OracleConnection : public IDBConnection{
};
class OracleCommand : public IDBCommand{
};
class OracleDataReader : public IDataReader{
};
class EmployeeDAO{
IDBConnectionFactory* dbConnectionFactory;
IDBCommandFactory* dbCommandFactory;
IDataReaderFactory* dataReaderFactory;
public:
vector<EmployeeDO> GetEmployees(){
IDBConnection* connection =
dbConnectionFactory->CreateDBConnection();
connection->ConnectionString("...");
IDBCommand* command =
dbCommandFactory->CreateDBCommand();
command->CommandText("...");
command->setConnection(connection); //相关性
IDBDataReader* reader = command->ExecuteReader(); //相关性
while(reader->Read()){
}
}
};
问题:使用者可能传入dbConnectionFactory是sqlserver的,但是dbCommandFactory是mysql的。
EmployeeDAO3.cpp
//数据库访问有关的基类
class IDBConnection{
};
class IDBCommand{
};
class IDataReader{
};
class IDBFactory{
public:
virtual IDBConnection* CreateDBConnection() = 0; //思想:将这3个关联的放到一起
virtual IDBCommand* CreateDBCommand() = 0;
virtual IDataReder* CreateDataReader() = 0;
};
//支持Sql server
class SqlConnection : public IDBConnection{
};
class SqlCommand : public IDBCommand{
};
class SqlDataReader : public IDataReader{
};
//具体工厂
class SqlDBFactory : public IDBFactory{
virtual IDBConnection* CreateDBConnection(){
}
virtual IDBCommand* CreateDBCommand(){}
virtual IDataReder* CreateDataReader(){}
};
//支持Oracle
class OracleConnection : public IDBConnection{
};
class OracleCommand : public IDBCommand{
};
class OracleDataReader : public IDataReader{
};
//具体工厂
class OracleDBFactory : public IDBFactory{
virtual IDBConnection* CreateDBConnection(){
}
virtual IDBCommand* CreateDBCommand(){}
virtual IDataReder* CreateDataReader(){}
};
class EmployeeDAO{
IDBFactory* dbFactory;
public:
vector<EmployeeDO> GetEmployees(){
IDBConnection* connection =
dbFactory->CreateDBConnection();
connection->ConnectionString("...");
IDBCommand* command =
dbFactory->CreateDBCommand();
command->CommandText("...");
command->setConnection(connection); //相关性
IDBDataReader* reader = command->ExecuteReader(); //相关性
while(reader->Read()){
}
}
};
模式定义:
结构:
标识图:
A B C表示IDBConnection IDBCommand IDBDataReader
1 2 3 代表 sqlserver Oracle等