对所有组件统一封装,并按一定的顺序组装使用
#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<<"Access 牌车轮"<<endl;}
};
class SqlServer:public Sql
{
public:
virtual ~SqlServer(){cout<<"SqlServer 析构"<<endl;}
virtual void Do(){cout<<"SqlServer 牌车轮"<<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 牌油箱"<<endl;};
};
class DepartmentServer:public Department
{
public:
virtual ~DepartmentServer(){cout<<"DepartmentServer 析构"<<endl;}
virtual void Did(){cout<<"DepartmentServer 牌油箱"<<endl;};
};
class Builder
{
public:
virtual ~Builder(){cout<<"Builder 基类析构"<<endl;}
virtual Sql* BuilderSql() = 0;
virtual Department* BuilderDepartment() = 0;
};
class BuilderAccess:public Builder
{
public:
virtual ~BuilderAccess(){cout<<"BuilderAccess 析构"<<endl;}
virtual Sql* BuilderSql(){return new SqlAccess;}
virtual Department* BuilderDepartment(){return new DepartmentAccess;}
};
class BuilderServer:public Builder
{
public:
virtual ~BuilderServer(){cout<<"BuilderServer 析构"<<endl;}
virtual Sql* BuilderSql(){return new SqlServer;}
virtual Department* BuilderDepartment(){return new DepartmentServer;}
};
class Director
{
Builder* pBui;
Sql* pSql;
Department* pDep;
public:
Director(Builder* p){pBui = p;}
~Director()
{
delete pBui;
delete pSql;
delete pDep;
}
void Construct()
{
pSql = pBui->BuilderSql();
pDep = pBui->BuilderDepartment();
}
void Process()
{
pSql->Do();
pDep->Did();
}
};
//生产摩托车的步骤是一样的
void Product(Director* pDir)
{
pDir->Construct();
pDir->Process();
}
int main(int argc, char *argv[])
{
//造一辆ACCESS牌的摩托车
cout<<"---------------------造一辆ACCESS牌的摩托车"<<endl;
Director* pDir = new Director(new BuilderAccess);
Product(pDir);
cout<<"---------------------清理制造ACCESS摩托车产生的垃圾"<<endl;
delete pDir;
//造一辆Server牌的摩托车
cout<<"---------------------造一辆Server牌的摩托车"<<endl;
pDir = new Director(new BuilderServer);
Product(pDir);
cout<<"---------------------清理制造Server摩托车产生的垃圾"<<endl;
delete pDir;
system("PAUSE");
return EXIT_SUCCESS;
}