天天看點

建造者(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;
}
           

繼續閱讀