用 C plus plus 写一个建造者模式
时间: 2023-10-01 21:02:11 浏览: 92
好的,您可以参考以下代码实现:
```C++
#include<iostream>
using namespace std;
//产品类
class Product
{
public:
void setPartA(const string& s)
{
partA = s;
}
void setPartB(const string& s)
{
partB = s;
}
void setPartC(const string& s)
{
partC = s;
}
void show()
{
cout << "PartA:" << partA << endl;
cout << "PartB:" << partB << endl;
cout << "PartC:" << partC << endl;
}
private:
string partA;
string partB;
string partC;
};
//抽象建造者
class Builder
{
public:
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual void buildPartC() = 0;
virtual Product* getResult() = 0;
};
//具体建造者
class ConcreteBuilder : public Builder
{
public:
ConcreteBuilder()
{
product = new Product();
}
void buildPartA()
{
product->setPartA("A");
}
void buildPartB()
{
product->setPartB("B");
}
void buildPartC()
{
product->setPartC("C");
}
Product* getResult()
{
return product;
}
private:
Product* product;
};
//指挥者
class Director
{
public:
Director(Builder* builder)
{
this->builder = builder;
}
void construct()
{
builder->buildPartA();
builder->buildPartB();
builder->buildPartC();
}
private:
Builder* builder;
};
int main()
{
Builder* builder = new ConcreteBuilder();
Director* director = new Director(builder);
director->construct();
Product* product = builder->getResult();
product->show();
return 0;
}
```
以上就是一个用C++编写的建造者模式的实现,希望能够对您有所帮助!
阅读全文