抽象工厂最主要的特点就是,一个工厂产生一类相关对象,
这些对象互相依赖,共同发挥作用
#include <cstdlib>
#include <iostream>
using namespace std;
class Sql
{
public:
virtual ~Sql(){cout<<"Sql 基类析构"<<endl;}
virtual void Do() = 0;
};
class SqlAccess:public Sql
{
public:
virtual ~SqlAccess(){cout<<"SqlAccess 析构"<<endl;}
virtual void Do(){cout<<"SqlAccess do something"<<endl;}
};
class SqlServer:public Sql
{
public:
virtual ~SqlServer(){cout<<"SqlServer 析构"<<endl;}
virtual void Do(){cout<<"SqlServer do something"<<endl;}
};
class Department
{
public:
virtual ~Department(){cout<<"Department 基类析构"<<endl;}
virtual void Did() = 0;
};
class DepartmentAccess:public Department
{
public:
virtual ~DepartmentAccess(){cout<<"DepartmentAccess 析构"<<endl;}
virtual void Did(){cout<<"DepartmentAccess do something"<<endl;};
};
class DepartmentServer:public Department
{
public:
virtual ~DepartmentServer(){cout<<"DepartmentServer 析构"<<endl;}
virtual void Did(){cout<<"DepartmentServer do something"<<endl;};
};
class Factory
{
public:
virtual ~Factory(){}
virtual Sql* CreateSql() = 0;
virtual Department* CreateDepartment() = 0;
};
class AccessFactory:public Factory
{
public:
virtual ~AccessFactory(){}
virtual Sql* CreateSql(){return new SqlAccess;}
virtual Department* CreateDepartment(){return new DepartmentAccess;}
};
class ServerFactory:public Factory
{
public:
virtual ~ServerFactory(){}
virtual Sql* CreateSql(){return new SqlServer;}
virtual Department* CreateDepartment(){return new DepartmentServer;}
};
void DoSth(Factory* pFac)
{
Sql* pSql = pFac->CreateSql();
Department* pDep = pFac->CreateDepartment();
pSql->Do();
pDep->Did();
delete pSql;
delete pDep;
}
int main(int argc, char *argv[])
{
AccessFactory fac;
DoSth(&fac);
ServerFactory sfac;
DoSth(&sfac);
system("PAUSE");
return EXIT_SUCCESS;
}