建造者模式

      建造者模式即将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

      建造者模式的结构图如下:


     实用范围:

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 ;

}
       最后的输出结果为:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值