建造者模式
建造者模式时对象的构建过程抽象出来,与实现分离。针对一类特殊对象,他们的有着共同的构建过程,也就是需要经过同样的步骤才能得到。但由于每个步骤使用参数的不同,使之得到的对象也不同。
抽象不依赖于细节,细节依赖于抽象这句化说明了实现与抽象之间的关系。
举个栗子: 我们需要画一个人,有固定的步骤:
1. 画头(Head)
2. 画五官(features)
3. 画身体(body)
4. 画胳膊(arm)
5. 画腿(lag)
6. 画脚(foot)
虽然每种不同的人有不同的特征,但构建过程一致,由于过程中加入的参数不同,所以有不同的内部表示。
以抽象的眼光来看待这个问题。我们需要创建不同的对象,我们知道他们的创建过程时一样的,使用这种共性作为抽象来派生他们。我们需要创建他们时使用基类对象,在指挥者来进行逐步的执行。完成对象的创建。
其中Human类作为抽象类,对ThinHuman, FatHuman类的抽象。使用Direct作为创建者,使用Human指针对具体类对象进行实例化。
#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;
}