#include <iostream>
using namespace std;
enum SEX_E
{
SEX_F,
SEX_M
};
enum ROLE_E
{
ROLE_STUDENT,
ROLE_WORKER,
ROLE_BUTT
};
class Person
{
public:
int mAge;
SEX_E mSex;
ROLE_E mRole;
string mSchool;
string mCompany;
void print()
{
cout << "mAge" << ":\t" << mAge << endl;
cout << "mSex" << ":\t" << mSex << endl;
cout << "mRole" << ":\t" << mRole << endl;
cout << "mSchool" << ":\t" << mSchool.c_str() << endl;
cout << "mCompany" << ":\t" << mCompany.c_str() << endl;
}
};
class Builder
{
public:
Person* BuildWorker(int age, SEX_E sex, string extendInfo)
{
Person* pstPerson = new Person();
if (nullptr == pstPerson)
{
return nullptr;
}
pstPerson->mAge = age;
pstPerson->mSex = sex;
pstPerson->mRole = ROLE_WORKER;
pstPerson->mCompany = extendInfo;
return pstPerson;
}
Person* BuildStudent(int age, SEX_E sex, string extendInfo)
{
Person* pstPerson = new Person();
if (nullptr == pstPerson)
{
return nullptr;
}
pstPerson->mAge = age;
pstPerson->mSex = sex;
pstPerson->mRole = ROLE_STUDENT;
pstPerson->mSchool = extendInfo;
return pstPerson;
}
};
class Director
{
public:
Person* buildPerson(int age, SEX_E sex, ROLE_E role, string extendInfo)
{
Builder* pstBuilder = new Builder();
if (nullptr == pstBuilder)
{
return nullptr;
}
Person* pstPerson = nullptr;
if (ROLE_STUDENT == role)
{
pstPerson = pstBuilder->BuildStudent(age, sex, extendInfo);
}
else if (ROLE_WORKER == role)
{
pstPerson = pstBuilder->BuildWorker(age, sex, extendInfo);
}
delete pstBuilder;
pstBuilder = nullptr;
return pstPerson;
}
};
int main()
{
cout << "enter" << endl;
Director *pstDirector = new Director();
if (nullptr == pstDirector)
{
cout << "new director failed." << endl;
return -1;
}
Person* pstStudent = pstDirector->buildPerson(10, SEX_F, ROLE_STUDENT, "primary school");
if (nullptr == pstStudent)
{
cout << "build student failed." << endl;
delete pstDirector;
pstDirector = nullptr;
return -1;
}
pstStudent->print();
delete pstStudent;
pstStudent = nullptr;
Person* pstWorker = pstDirector->buildPerson(30, SEX_M, ROLE_WORKER, "scientific and technical corporation");
if (nullptr == pstWorker)
{
cout << "build worker failed." << endl;
delete pstDirector;
pstDirector = nullptr;
return -1;
}
pstWorker->print();
delete pstWorker;
pstWorker = nullptr;
delete pstDirector;
pstDirector = nullptr;
cout << "exit" << endl;
return 0;
}
执行结果
PS E:\workspace\sample\Builder> g++ main.cpp
PS E:\workspace\sample\Builder> ./a
enter
mAge: 10
mSex: 0
mRole: 0
mSchool: primary school
mCompany:
mAge: 30
mSex: 1
mRole: 1
mSchool:
mCompany: scientific and technical corporation
exit