按照软考中级软件设计师中指定的生成器模式uml图,可编写对应的C++代码:
#include<iostream>
#include<vector>
#include<string>
using namespace std;/*创建者模式,又名生成器模式意图:将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示
*///产品类
class Product{
public:vector<string> m_partVec;void add(string part){m_partVec.push_back(part);}void show(){for(int i = 0; i < m_partVec.size(); i++){cout<<m_partVec[i]<<endl;}}
};//生成器,纯虚函数,相当于java中的抽象类
class Builder{
public:virtual ~Builder(){}virtual void buildPart() const = 0;
};//具体的生成器,即实现不同的套餐
class Builder1 : public Builder{
private:Product* m_product = new Product();
public:~Builder1(){delete m_product;}void buildPart() const override{m_product->add("partA");}Product* getProduct(){return m_product;}
};//具体的生成器,即实现不同的套餐
class Builder2 : public Builder{
private:Product* m_product = new Product();
public:~Builder2(){delete m_product;}void buildPart() const override{m_product->add("partB");}Product* getProduct(){return m_product;}
};//主管,负责生成不同的套餐
class Director{
private:Builder* m_builder;
public:void setBuilder(Builder* builder){m_builder = builder;}void constrctor(){m_builder->buildPart();}
};int main()
{Director* director = new Director();cout<<"套餐A包含:"<<endl;Builder1* builder1 = new Builder1();director->setBuilder(builder1);director->constrctor();Product* product = builder1->getProduct();product->show();delete product;delete builder1;cout<<"套餐B包含:"<<endl;Builder2* builder2 = new Builder2();director->setBuilder(builder2);director->constrctor();product = builder2->getProduct();product->show();delete product;delete builder2;return 0;
}
执行结果: