c++实现建造者模式

代码

director.h

cpp 复制代码
#pragma once
#include<vector>
#include<string>
#include<iostream>

class Product
{
private:
	std::vector<std::string> _parts;

public:
	void Add(const std::string& part) {
		_parts.push_back(part);
	}

	void show()
	{
		std::cout << "product produce----" << std::endl;
		for (auto item : _parts) {
			std::cout << item << std::endl;
		}
		std::cout << std::endl;
	}
};

class Builder
{
public:
	virtual void buildPartA() = 0;
	virtual void buildPartB() = 0;
	virtual Product* getResult() = 0;
};

class ConcreteBuilder1 : public Builder
{
private:
	Product* _pProduct;

public:
	ConcreteBuilder1() {
		_pProduct = new Product();
	}
	~ConcreteBuilder1() {
		delete _pProduct;
	}

	void buildPartA() override
	{
		_pProduct->Add("部件a");
	}

	void buildPartB() override
	{
		_pProduct->Add("部件b");
	}

	// 小心使用。如果该类的对象被析构,得到的指针将为空。
	Product* getResult() override
	{
		if (_pProduct != nullptr) {
			return _pProduct;
		}
		else {
			return nullptr;
		}
	}
};

class ConcreteBuilder2 : public Builder
{
private:
	Product* _pProduct;

public:
	ConcreteBuilder2() {
		_pProduct = new Product();
	}
	~ConcreteBuilder2() {
		delete _pProduct;
	}

	void buildPartA() override
	{
		_pProduct->Add("部件x");
	}

	void buildPartB() override
	{
		_pProduct->Add("部件y");
	}

	// 小心使用。如果该类的对象被析构,得到的指针将为空。
	Product* getResult() override
	{
		if (_pProduct != nullptr) {
			return _pProduct;
		}
		else {
			return nullptr;
		}
	}

};


class Director
{
private:
	Builder* _pBuilder;

public:
	Director(Builder* p_builder) :_pBuilder(p_builder) {}

	void construct()
	{
		if (_pBuilder != nullptr) {
			_pBuilder->buildPartA();
			_pBuilder->buildPartB();
		}
	}
	
};

main.cpp

cpp 复制代码
#include<iostream>
#include"Director.h"



int main()
{
	Builder* pBuilder1 = new ConcreteBuilder1();

	Director* pDirector = new Director(pBuilder1);
	pDirector->construct(); // 让按builder1的方式生成产品

	Product* pProduct = pBuilder1->getResult();// 获取产品
	pProduct->show();

	Builder* pBuilder2 = new ConcreteBuilder2();
	pDirector = new Director(pBuilder2);
	pDirector->construct(); // 让按builder2的方式生成产品

	pProduct = pBuilder2->getResult(); // 获取产品
	pProduct->show();

	delete pDirector;
	delete pBuilder1;

	return 0;
}
相关推荐
漫漫进阶路2 小时前
VS C++ 配置OPENCV环境
开发语言·c++·opencv
陈平安Java and C2 小时前
MyBatisPlus
java
秋野酱3 小时前
如何在 Spring Boot 中实现自定义属性
java·数据库·spring boot
Bunny02123 小时前
SpringMVC笔记
java·redis·笔记
feng_blog66884 小时前
【docker-1】快速入门docker
java·docker·eureka
枫叶落雨2225 小时前
04JavaWeb——Maven-SpringBootWeb入门
java·maven
m0_748232395 小时前
SpringMVC新版本踩坑[已解决]
java
码农小灰5 小时前
Spring MVC中HandlerInterceptor和Filter的区别
java·spring·mvc
hefaxiang5 小时前
【C++】函数重载
开发语言·c++·算法
花生树什么树6 小时前
下载Visual Studio Community 2019
c++·visual studio·vs2019·community