建造者模式(Builder),将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
说明:
#include "product.h"
class Builder
{
public:
Builder();
virtual ~Builder(){}
virtual void AddPartA();
virtual void AddPartB();
Product* GetProduct();
protected:
Product* m_Product;
};
#include <iostream>
#include "builder.h"
Builder::Builder()
{
m_Product = new Product();
}
void Builder::AddPartA()
{
m_Product->AddPart("PartA");
}
void Builder::AddPartB()
{
m_Product->AddPart("PartB");
}
Product* Builder::GetProduct()
{
if(m_Product->PartsCount() > 0)
return m_Product;
else
std::cout << "产品还未组装好" << std::endl;
}
#include "builder.h"
class ConcreteBuilder1 : public Builder
{
public:
ConcreteBuilder1();
void AddPartA() override;
void AddPartB() override;
};
#include "concretebuilder1.h"
ConcreteBuilder1::ConcreteBuilder1()
{
}
void ConcreteBuilder1::AddPartA()
{
m_Product->AddPart("Part1");
}
void ConcreteBuilder1::AddPartB()
{
m_Product->AddPart("Part2");
}
#include "builder.h"
class Director
{
public:
Director();
void Construct(Builder* builder);
};
#include "director.h"
Director::Director()
{
}
void Director::Construct(Builder *builder)
{
builder->AddPartA();
builder->AddPartB();
}
#include <list>
#include <string>
class Product
{
public:
Product();
void AddPart(std::string part);
void Show();
int PartsCount();
private:
std::list<std::string> m_Parts;
};
#include "product.h"
#include <iostream>
Product::Product()
{
}
void Product::AddPart(std::string part)
{
m_Parts.push_back(part);
}
void Product::Show()
{
std::cout << "组成部分:" << std::endl;
for(auto part : m_Parts)
{
std::cout << part << std::endl;
}
}
int Product::PartsCount()
{
return m_Parts.size();
}
#include <iostream>
#include <memory>
#include "concretebuilder1.h"
#include "concretebuilder2.h"
#include "director.h"
using namespace std;
int main()
{
std::shared_ptr<Builder> builder1 = std::make_shared<ConcreteBuilder1>();
std::shared_ptr<Builder> builder2 = std::make_shared<ConcreteBuilder2>();
Director director;
director.Construct(builder1.get());
Product* product1 = builder1->GetProduct();
product1->Show();
director.Construct(builder2.get());
Product* product2 = builder2->GetProduct();
product2->Show();
return 0;
}
组成部分:
Part1
Part2
组成部分:
PartX
PartY
建造者模式的优点
模式的缺点
原文:https://www.cnblogs.com/wzxNote/p/13307163.html