C++ 设计模式 建造者模式

2,120 阅读2分钟

(4条消息) 建一栋房子总共分几步?建造者模式告诉你答案!_冯Jungle的个人博客-CSDN博客

建造者模式结构

建造者模式的结构包含以下几个角色:

  • 抽象建造者(AbstractBuilder) :创建一个Product对象的各个部件指定的抽象接口;
  • 具体建造者(ConcreteBuilder) :实现AbstractBuilder的接口,实现各个部件的具体构造方法和装配方法,并返回创建结果。
  • 产品(Product) :具体的产品对象
  • 指挥者(Director) : 构建一个使用Builder接口的对象,安排复杂对象的构建过程,客户端一般只需要与Director交互,指定建造者类型,然后通过构造函数或者setter方法将具体建造者对象传入Director。它主要作用是:隔离客户与对象的生产过程,并负责控制产品对象的生产过程。

建造者模式UML类图如下:

3.建造者模式代码实例

考虑这样一个场景,如下图:

Jungle想要建造一栋简易的房子(地板、墙和天花板),两个工程师带着各自的方案找上门来,直接给Jungle看方案和效果图。犹豫再三,Jungle最终选定了一位工程师……交房之日,Jungle满意的看着建好的房子,开始思考:这房子究竟是怎么建成的呢?这地板、墙和天花板是怎么建造的呢?工程师笑着说:“It's none of your business”

 UML图如下: image.png

//产品类House
class House
{
public:
	House(){}
	void setFloor(string iFloor){
		this->floor = iFloor;
	}
	void setWall(string iWall){
		this->wall = iWall;
	}
	void setRoof(string iRoof){
		this->roof = iRoof;
	}
	//打印House信息
	void printfHouseInfo(){
		printf("Floor:%s\t\n", this->floor.c_str());
		printf("Wall:%s\t\n", this->wall.c_str());
		printf("Roof:%s\t\n", this->roof.c_str());
	}
private:
	string floor;
	string wall;
	string roof;
};
//抽象建造者AbstractBall
class AbstractBuilder
{
public:
	AbstractBuilder(){
		house = new House();
	}
	//抽象方法:
	virtual void buildFloor() = 0;
	virtual void buildWall() = 0;
	virtual void buildRoof() = 0;
	virtual House *getHouse() = 0;
 
	House *house;
};
//具体建造者ConcreteBuilderA
class ConcreteBuilderA :public AbstractBuilder
{
public:
	ConcreteBuilderA(){
		printf("ConcreteBuilderA\n");
	}
	//具体实现方法
	void buildFloor(){
		this->house->setFloor("Floor_A");
	}
	void buildWall(){
		this->house->setWall("Wall_A");
	}
	void buildRoof(){
		this->house->setRoof("Roof_A");
	}
	House *getHouse(){
		return this->house;
	}
};
 
//具体建造者ConcreteBuilderB
class ConcreteBuilderB :public AbstractBuilder
{
public:
	ConcreteBuilderB(){
		printf("ConcreteBuilderB\n");
	}
	//具体实现方法
	void buildFloor(){
		this->house->setFloor("Floor_B");
	}
	void buildWall(){
		this->house->setWall("Wall_B");
	}
	void buildRoof(){
		this->house->setRoof("Roof_B");
	}
	House *getHouse(){
		return this->house;
	}
};
//指挥者Director
class Director
{
public:
	Director(){}
	//具体实现方法
	void setBuilder(AbstractBuilder *iBuilder){
		this->builder = iBuilder;
	}
        //封装组装流程,返回建造结果
	House *construct(){
		builder->buildFloor();
		builder->buildWall();
		builder->buildRoof();
		return builder->getHouse();
	}
private:
	AbstractBuilder *builder;
};

客户端代码示例

#include "BuilderPattern.h"
 
int main()
{
	//抽象建造者
	AbstractBuilder *builder;
	//指挥者
	Director *director = new Director();
	//产品:House
	House *house;
 
	//指定具体建造者A
	builder = new ConcreteBuilderA();
	director->setBuilder(builder);
	house = director->construct();
	house->printfHouseInfo();
 
	//指定具体建造者B
	builder = new ConcreteBuilderB();
	director->setBuilder(builder);
	house = director->construct();
	house->printfHouseInfo();
 
	system("pause");
	return 0;
}
  • 效果

image.png