![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7d99913da66a58ab3f059719b724364d.png)
代码
director.h
#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
#include<iostream>
#include"Director.h"
int main()
{
Builder* pBuilder1 = new ConcreteBuilder1();
Director* pDirector = new Director(pBuilder1);
pDirector->construct();
Product* pProduct = pBuilder1->getResult();
pProduct->show();
Builder* pBuilder2 = new ConcreteBuilder2();
pDirector = new Director(pBuilder2);
pDirector->construct();
pProduct = pBuilder2->getResult();
pProduct->show();
delete pDirector;
delete pBuilder1;
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6ed9ebec0cb64383760a17ea7c5aa97f.png)