抽象工厂模式解决的是一系列相互依赖的对象的创建。
class MyConnect {
};
class MyDatabse {
};
class MyCommand {
};
//sqlServer的连接
class SqlServerConnect :public MyConnect {
};
class SqlServerDatabse :public MyDatabse {
};
class SqlServerCommand :public MyCommand {
};
class MyFactory {
virtual MyConnect* createConnectInstance() = 0;
virtual MyDatabse* createDatabseInstance() = 0;
virtual MyCommand* createCommandInstance() = 0;
};
class SqlServerFactory :public MyFactory {
public:
MyConnect* createConnectInstance() {
if (sqlServerConnect == nullptr) {
sqlServerConnect = new SqlServerConnect();
}
return sqlServerConnect;
}
MyDatabse* createDatabseInstance() {
if (sqlServerDatabse == nullptr) {
sqlServerDatabse = new SqlServerDatabse();
}
return sqlServerDatabse;
}
MyCommand* createCommandInstance() {
if (sqlServerCommand == nullptr) {
sqlServerCommand = new SqlServerCommand();
}
return sqlServerCommand;
}
private:
SqlServerConnect* sqlServerConnect;
SqlServerDatabse* sqlServerDatabse;
SqlServerCommand* sqlServerCommand;
};
这里就创建了自己的数据库的连接器数据库和命令类,这些类之间都是有关联的,我这里定义的MyFactory就可以创建一系列相关联的对象来供我们使用。