建造者模式c++实例代码
时间: 2023-10-18 19:04:07 浏览: 79
下面是一个简单的建造者模式的 C++ 示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 产品类
class Product {
public:
void setPartA(string partA) { m_partA = partA; }
void setPartB(string partB) { m_partB = partB; }
void setPartC(string partC) { m_partC = partC; }
void show() { cout << m_partA << " " << m_partB << " " << m_partC << endl; }
private:
string m_partA;
string m_partB;
string m_partC;
};
// 抽象建造者类
class Builder {
public:
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual void buildPartC() = 0;
virtual Product* getProduct() = 0;
};
// 具体建造者类
class ConcreteBuilder : public Builder {
public:
ConcreteBuilder() { m_product = new Product(); }
void buildPartA() { m_product->setPartA("PartA"); }
void buildPartB() { m_product->setPartB("PartB"); }
void buildPartC() { m_product->setPartC("PartC"); }
Product* getProduct() { return m_product; }
private:
Product* m_product;
};
// 指挥者类
class Director {
public:
void setBuilder(Builder* builder) { m_builder = builder; }
Product* construct() {
m_builder->buildPartA();
m_builder->buildPartB();
m_builder->buildPartC();
return m_builder->getProduct();
}
private:
Builder* m_builder;
};
int main() {
Director director;
ConcreteBuilder concreteBuilder;
director.setBuilder(&concreteBuilder);
Product* product = director.construct();
product->show();
delete product;
return 0;
}
```
在上面的代码中,Product 类表示要建造的产品,Builder 类是抽象建造者类,定义了建造产品的抽象方法,ConcreteBuilder 类是具体建造者类,实现了 Builder 类中定义的抽象方法,并返回 Product 对象,Director 类是指挥者类,用于指挥建造过程的顺序。在 main() 函数中,我们首先创建了一个 ConcreteBuilder 对象,然后通过 Director 类来完成建造过程,并最终获得了建造完成的 Product 对象并输出其属性。
阅读全文