使一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方式时适用的模式。
#include <iostream>
#include <memory>
#include <vector>
/* 产品类,构建的内容 */
class Product {
public:
void add(std::string part) { vec.emplace_back(part); }
void show() {
for (const auto &str : vec) {
std::cout << str << ' ';
}
std::cout << "\n";
}
private:
std::vector<std::string> vec;
};
class Builder {
public:
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual Product getProduct() = 0;
};
class ConcreteBuilder1 final : public Builder {
public:
void buildPartA() override { pro.add("part A"); }
void buildPartB() override { pro.add("part B"); }
Product getProduct() override { return pro; }
private:
Product pro;
};
/* 具体建造者 */
class ConcreteBuilder2 final : public Builder {
public:
void buildPartA() override { pro.add("part X"); }
void buildPartB() override { pro.add("part Y"); }
Product getProduct() override { return pro; }
private:
Product pro;
};
/* 指挥者类,用于指挥构造 */
class Director {
public:
void Construct(const std::shared_ptr<Builder> &builder) {
builder->buildPartA();
builder->buildPartB();
}
};
auto main() -> int {
Director director;
std::shared_ptr<Builder> b1 = std::make_shared<ConcreteBuilder1>();
std::shared_ptr<Builder> b2 = std::make_shared<ConcreteBuilder2>();
director.Construct(b1);
Product p1 = b1->getProduct();
p1.show();
director.Construct(b2);
Product p2 = b2->getProduct();
p2.show();
return 0;
}