目录
1. 描述
将构造和表示分离,构造过程一样,但是构造结果不一样。
2. 特点
1) 过程确定,但是构造细节可以变化,将细节隔离出去,有利于系统的拓展
2) 客户端不必要迟到内部组成细节,控制细节风险
3. 缺点
1)过程确定
4.要素
1) 产品:对建造成果的展示。
2)抽象建造者:
3)建造者:对产品的各个组件进行构建
4)指挥官:将建造者的方法形成流程。
5.UML
6. 示例
#include "stdafx.h"
#include <iostream>
//1. 产品
class Parlour//客厅
{
public:
void SetWall(std::string wall)
{
_Wall = wall;
}
void SetTV(std::string tv)
{
_TV = tv;
}
void Show()
{
std::cout << "客厅墙颜色:" << _Wall.c_str() << " 电视品牌:" << _TV.c_str() << std::endl;
}
private:
std::string _Wall;
std::string _TV;
};
//2. 抽象建造者
class Decorator
{
public:
Decorator()
{
_Parlour = new Parlour;
}
Parlour * GetResult()
{
return _Parlour;
}
virtual void BuildWall() = 0;
virtual void BuildTV() = 0;
protected:
Parlour * _Parlour;
};
//3. 具体建造者
class ConcreteDecorator1 :public Decorator
{
void BuildWall()
{
_Parlour->SetWall("黄色");
};
void BuildTV()
{
_Parlour->SetTV("海尔");
};
};
//5. 指挥官
class ProjectMananger
{
public:
ProjectMananger (Decorator * decorator)
{
_Decorator = decorator;
}
Parlour * decoratr()
{
_Decorator->BuildWall();
_Decorator->BuildTV();
return _Decorator->GetResult();
}
private:
Decorator * _Decorator;
};
int main()
{
//建造者建造细节
ConcreteDecorator1 * CD1 = new ConcreteDecorator1;
//对细节管理和封装
ProjectMananger projectMananger(CD1 );
//返回建造结果
Parlour * parlour = projectMananger.decoratr();
//建造成品的展示
parlour->Show();
getchar();
return 0;
}