#pragma once
#include
#include
#include
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();
}
}
};
#include
#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;
}