生成器模式
#include <iostream> #include <memory> class Product { public: void setPartA(int partA) { this->partA = partA; } void setPartB(int partB) { this->partB = partB; } void setPartC(int partC) { this->partC = partC; } void show() { std::cout << "In Product. partA is " << partA << ". partB is " << partB << ". partC is " << partC << "." << std::endl; } private: int partA = 0; int partB = 0; int partC = 0; }; class Builder { public: virtual void buildPartA() = 0; virtual void buildPartB() = 0; virtual void buildPartC() = 0; Product getResult() { return p; } protected: Product p; }; class ConcreteBuilder1 : public Builder { public: void buildPartA() override { p.setPartA(1); } void buildPartB() override { p.setPartB(2); } void buildPartC() override { p.setPartC(3); } }; class ConcreteBuilder2 : public Builder { public: void buildPartA() override { p.setPartA(7); } void buildPartB() override { p.setPartB(8); } void buildPartC() override { p.setPartC(9); } }; class Director { public: void setBuilder(std::shared_ptr<Builder> b) { this->b = b; } Product construct(void) { b->buildPartA(); b->buildPartB(); b->buildPartC(); return b->getResult(); } private: std::shared_ptr<Builder> b; }; int main(int argc, char *argv[]) { Director d; std::shared_ptr<Builder> b = std::make_shared<ConcreteBuilder1>(); d.setBuilder(b); Product p = d.construct(); p.show(); b = std::make_shared<ConcreteBuilder2>(); d.setBuilder(b); p = d.construct(); p.show(); return 1; }