特点:如何创建一个组合的对象
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Product {
public:
<string>vec;
vector& operator<<(ostream& os) {
ostreamfor (const auto& item : vec) {
<< item << " ";
os }
return os;
}
};
class Builder {
public:
virtual ~Builder() {}
virtual Builder* processA() = 0;
virtual Builder* processB() = 0;
virtual Builder* processC() = 0;
};
class MyBuilder:public Builder{
public:
~MyBuilder() {
delete ptr;
}
():ptr(nullptr) {
MyBuilder();
reset}
void reset() {
= new Product;
ptr }
* processA() override {
Builder->vec.push_back("process A");
ptrreturn this;
}
* processB() override {
Builder->vec.push_back("process B");
ptrreturn this;
}
* processC() override {
Builder->vec.push_back("process C");
ptrreturn this;
}
* get() {
Product* ptrTemp = ptr;
Product();//创建新的对象实例
resetreturn ptrTemp;//将装配好的实例返回
}
private:
* ptr;
Product};
class Director {
private:
* mBuilder;
Builderpublic:
void setBuilder(Builder* builder) {
= builder;
mBuilder }
void buildMinimalProduct() {
->processA();
mBuilder}
void buildFullFeatureProduct() {
->processA()->processB()->processC();
mBuilder}
};
int main() {
* director = new Director;
Director* mBuilder = new MyBuilder;
MyBuilder->setBuilder(mBuilder);
director
->buildFullFeatureProduct();
director//内部调用builder提供的一系列接口
* p1=mBuilder->get();
Product->operator<<(cout);//process A process B process C
p1<< endl;
cout delete p1;
->buildMinimalProduct();
director* p2 = mBuilder->get();
Product->operator<<(cout);//process A
p2<< endl;
cout delete p2;
delete director;
delete mBuilder;
return 0;
}