设计模式之建造者模式(Builder)

时间:2022-03-28 20:44:32

建造者模式原理:建造模式主要是用于产生对象的各个组成部分,而抽象工厂模式则用于产生一系列对象,建造者模式而且要求这些对象的组成部分有序。

代码如下:

#include <iostream>
using namespace std; class Builder
{
public:
virtual void buildHead(){}
virtual void buildBody(){}
virtual void buildLeftArm(){}
virtual void buildRightArm(){}
virtual void buildLeftLeg(){}
virtual void buildRightLeg(){}
};
class BuilderFat:public Builder
{
public:
virtual void buildHead(){cout << "fat head" <<endl;}
virtual void buildBody(){cout << "fat Body" << endl;}
virtual void buildLeftArm(){cout << "fat Left Arm" <<endl;}
virtual void buildRightArm(){cout << "fat Right Arm" <<endl;}
virtual void buildLeftLeg(){cout << "fat Left Leg" <<endl;}
virtual void buildRightLeg(){cout << "fat Right leg" <<endl;}
}; class BuilerThin:public Builder
{
public:
virtual void buildHead(){cout << " thin head" <<endl;}
virtual void buildBody(){cout << "thin Body" << endl;}
virtual void buildLeftArm(){cout << "thin Left Arm" <<endl;}
virtual void buildRightArm(){cout << "thin Right Arm" <<endl;}
virtual void buildLeftLeg(){cout << "thin Left Leg" <<endl;}
virtual void buildRightLeg(){cout << "thin Right leg" <<endl;}
}; class Director
{
public:
Director(Builder *ptmp = NULL):pBuilder(ptmp)
{ }
void createPerson()
{
pBuilder->buildHead();
pBuilder->buildBody();
pBuilder->buildLeftArm();
pBuilder->buildRightArm();
pBuilder->buildRightArm();
pBuilder->buildLeftLeg();
pBuilder->buildRightLeg();
}
private:
Builder* pBuilder;
}; int main()
{
BuilderFat fat;
Director *pDirector = new Director(&fat);
pDirector->createPerson();
delete pDirector;
return 0;
}