提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
当需要创建一个复杂的对象,并且对象的建造顺序稳定时,为了使得建造代码和表示代码相分离,隐藏对象建造过程,可以使用建造者模式。类图示意如下:
其中builder类定义了对象建造使用的抽象接口,concretebuilder类定义了不同对象的具体接口,director类调用具体对象接口,按照一系列顺序建造对象。
代码如下(示例):
//14 建造者模式
class PersonBuilder
{
public:
virtual void createHead() = 0;
virtual void createBody() = 0;
virtual void createLeftArm() = 0;
virtual void createRightArm() = 0;
virtual void createLeftLeg() = 0;
virtual void createRightLeg() = 0;
};
class ThinPersionBuilder :public PersonBuilder
{
public:
void createHead() override
{
cout << "瓜子脸" << endl;
}
void createBody() override
{
cout << "竹竿腰" << endl;
}
void createLeftArm() override
{
cout << "迷人左臂" << endl;
}
void createRightArm() override
{
cout << "迷人右臂" << endl;
}
void createLeftLeg() override
{
cout << "180左腿" << endl;
}
void createRightLeg() override
{
cout << "180右腿" << endl;
}
};
class FatPersionBuilder :public PersonBuilder
{
public:
void createHead() override
{
cout << "圆圆脸" << endl;
}
void createBody() override
{
cout << "水桶腰" << endl;
}
void createLeftArm() override
{
cout << "健壮左臂" << endl;
}
void createRightArm() override
{
cout << "健壮右臂" << endl;
}
void createLeftLeg() override
{
cout << "粗壮左腿" << endl;
}
void createRightLeg() override
{
cout << "粗壮右腿" << endl;
}
};
class PersionDirector
{
public:
PersionDirector(PersonBuilder *ipBuilder) :m_pPersonBuilder(ipBuilder){};
void CreatePersion()
{
m_pPersonBuilder->createHead();
m_pPersonBuilder->createBody();
m_pPersonBuilder->createLeftArm();
m_pPersonBuilder->createRightArm();
m_pPersonBuilder->createLeftLeg();
m_pPersonBuilder->createRightLeg();
}
private:
PersonBuilder *m_pPersonBuilder;
};
暂无。