设计模式13-建造者模式

目录

1. 描述

2. 特点

3. 缺点

4.要素

5.UML

6. 示例


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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值