建造者(Builder)模式

建造者模式

建造者模式时对象的构建过程抽象出来,与实现分离。针对一类特殊对象,他们的有着共同的构建过程,也就是需要经过同样的步骤才能得到。但由于每个步骤使用参数的不同,使之得到的对象也不同。

抽象不依赖于细节,细节依赖于抽象这句化说明了实现与抽象之间的关系。

举个栗子: 我们需要画一个人,有固定的步骤:

1. 画头(Head)
2. 画五官(features)
3. 画身体(body)
4. 画胳膊(arm)
5. 画腿(lag)
6. 画脚(foot)

虽然每种不同的人有不同的特征,但构建过程一致,由于过程中加入的参数不同,所以有不同的内部表示。

以抽象的眼光来看待这个问题。我们需要创建不同的对象,我们知道他们的创建过程时一样的,使用这种共性作为抽象来派生他们。我们需要创建他们时使用基类对象,在指挥者来进行逐步的执行。完成对象的创建。

builder

其中Human类作为抽象类,对ThinHuman, FatHuman类的抽象。使用Direct作为创建者,使用Human指针对具体类对象进行实例化。

//Human.hpp

#include <string>
#include <iostream>
#ifndef _DESIGN_PATTERN_BUILDER_HUMAN_HPP_
#define _DESIGN_PATTERN_BUILDER_HUMAN_HPP_

namespace design_pattern
{

class Human
{
public:
	virtual void Head() = 0;
	virtual void Features() = 0;
	virtual void Body() = 0;
	virtual void Arm() = 0;
	virtual void Lag() = 0;
	virtual void Foot() = 0;
};

class ThinHuman : public Human
{
public:
	void Head()
	{
		std::cout << "Head";
	}
	void Features()
	{
		std::cout << "    Features";
	}
	void Body()
	{
		std::cout << "    Body Thin";
	}
	void Arm()
	{
		std::cout << "    Arm";
	}
	void Lag()
	{
		std::cout << "    Lag";
	}
	void Foot()
	{
		std::cout << "    Foot" << std::endl;
	}
};

class FatHuman : public Human
{
public:
	void Head()
	{
		std::cout << "Head";
	}
	void Features()
	{
		std::cout << "    Features";
	}
	void Body()
	{
		std::cout << "    Body Fat";
	}
	void Arm()
	{
		std::cout << "    Arm";
	}
	void Lag()
	{
		std::cout << "    Lag";
	}
	void Foot()
	{
		std::cout << "    Foot" << std::endl;
	}
};
}
#endif // !_DESIGN_PATTERN_BUILDER_HUMAN_HPP_

//builder_main.cpp

#include <iostream>
#include <memory>
#include "human.hpp"
#include "director.hpp"
using namespace design_pattern;
using std::cout;
using std::endl;
using std::unique_ptr;

int main()
{
	unique_ptr<Human> pthin(new ThinHuman);
	unique_ptr<Human> pfat(new FatHuman);
	Director dthin(pthin.get());
	Director dfat(pfat.get());

	dthin.Construct();
	dfat.Construct();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值