基本概念脑图
具体案例(Qt,C++)
利用建造者模式相关概念,通过头、身体、左手、右手、左脚和右脚等模块对火柴人模型进行组装,使其表现为瘦、胖、高等不同特性。
// 抽象类
class PersonBuilder
{
public:
PersonBuilder();
~PersonBuilder();
//PersonBuilder(QPaintDevice *device);
virtual void BuildHead()=0;
virtual void BuildBody()=0;
virtual void BuildArmLeft()=0;
virtual void BuildArmRight()=0;
virtual void BuildLegLeft()=0;
virtual void BuildLegRighe()=0;
private:
//QPainter *p;
};
//继承于抽象类的瘦人类
class PersonThinBulider:public PersonBuilder
{
public:
PersonThinBulider(QPainter *p){
this->p=p;
}
void BuildHead(){
p->drawEllipse(50,20,30,30);
}
void BuildBody(){
p->drawRect(60,50,10,50);
}
void BuildArmLeft(){
p->drawLine(60,50,40,100);
}
void BuildArmRight(){
p->drawLine(70,50,90,100);
}
void BuildLegLeft(){
p->drawLine(60,100,45,150);
}
void BuildLegRighe(){
p->drawLine(70,100,85,150);
}
private:
QPainter *p;
};
//继承于抽象类的胖人类
class PersonFatBulider:public PersonBuilder
{
public:
PersonFatBulider(QPainter *p){
p->setPen(Qt::red);
this->p=p;
}
void BuildHead(){
p->drawEllipse(50,20,30,30);
}
void BuildBody(){
p->drawEllipse(45,50,40,50);
}
void BuildArmLeft(){
p->drawLine(50,50,30,100);
}
void BuildArmRight(){
p->drawLine(80,50,100,100);
}
void BuildLegLeft(){
p->drawLine(60,100,45,150);
}
void BuildLegRighe(){
p->drawLine(70,100,85,150);
}
private:
QPainter *p;
};
//指挥者用于控制建造过程
class PersonDirector
{
public:
// 用户初始化指挥者
PersonDirector(PersonBuilder *pb){
this->pb=pb;
}
// 根据用户的选择建造人类
void CreatePerson()
{
pb->BuildHead();
pb->BuildBody();
pb->BuildArmLeft();
pb->BuildArmRight();
pb->BuildLegLeft();
pb->BuildLegRighe();
}
private:
PersonBuilder *pb;
};
实现效果
代码
code
关于作者
长期从事编程相关研究,涉及Qt、机械臂、轮式机器人、四足机器人的建模及仿真,可共同探讨编程相关问题,可指导课程设计及毕业设计,详询:QQ:2963325158