建造者模式即将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
建造者模式的结构图如下:
实用范围:
1 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
2 当构造过程必须允许被构造的对象有不同表示时。
下面是利用建造者模式实现画出不同类型的人的代码,更加直观的体现出建造者模式的特点:
#include <iostream>
using namespace std ;
class Person //抽象类 人类
{
public:
virtual void Draw_head() = 0 ; //纯虚函数 画头
virtual void Draw_body() = 0 ; //纯虚函数 画身体
virtual void Draw_arm() = 0 ; //纯虚函数 画手臂
virtual void Draw_leg() = 0 ; //纯虚函数 画腿
};
class FatPerson : public Person //肥胖者
{
public:
void Draw_head()
{
cout<<"画肥胖者的头"<<endl ; //实现纯虚函数 画头
}
void Draw_body()
{
cout<<"画肥胖者的身体"<<endl ;
}
void Draw_arm()
{
cout<<"画肥胖者的手臂"<<endl ;
}
void Draw_leg()
{
cout<<"画肥胖者的腿"<<endl ;
}
};
class SlimPerson : public Person //苗条的人
{
public:
void Draw_head()
{
cout<<"画苗条者的头"<<endl ; //实现纯虚函数 画头
}
void Draw_body()
{
cout<<"画苗条者的身体"<<endl ;
}
void Draw_arm()
{
cout<<"画苗条者的手臂"<<endl ;
}
void Draw_leg()
{
cout<<"画苗条者的腿"<<endl ;
}
};
class Director //指导者
{
Person * pPerson ;
public:
Director(Person * myPerson):pPerson(myPerson){} //构造函数
void Drawing()
{
pPerson->Draw_body() ;
pPerson->Draw_body() ;
pPerson->Draw_arm() ;
pPerson->Draw_leg() ;
}
};
int main()
{
cout<<"肥胖者:"<<endl ;
FatPerson * pFatPerson = new FatPerson ;
Director * pDirector = new Director(pFatPerson) ; //画出一个肥胖者
pDirector->Drawing() ;
cout<<endl ;
cout<<"苗条者:"<<endl ;
SlimPerson * pSlim = new SlimPerson ;
Director * pDirector2 = new Director(pSlim) ; //画出一个苗条的人
pDirector2->Drawing() ;
return 0 ;
}
最后的输出结果为: