概述
建造者模式:将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
建造者模式其实就是在创建复杂对象时,使用一个Builder类(建造者类)来规范了必要的步骤,并且使用一个Director类(指挥类)来规范建造过程。
应用场景
一些基本部件不会变,而其组合经常变化的时候。例如:画一个小人,小人的基本部件(头、身体、两只手、两只脚)以及画的过程一般都不会变的;而画瘦子或胖子就需要改变画的方法了。
一般步骤
1.写一个Builder类来规范必要的步骤,每个步骤都是纯虚函数,所以子类必须重写,没有重写则编译不过,所以每个必要的步骤都实现了,不会漏掉哪个步骤;
// 建造者类-规范了必要的步骤,因为都是纯虚函数,所以子类必须重写,否则编译不过 class Builder { public: virtual void BuildPartA() = 0; virtual void BuildPartB() = 0; virtual Product *GetResult() = 0; };
2.写子类,继承Builder类,并实现必要的步骤;
class ConcreatBuilder1 : public Builder { private: Product *product; public: ConcreatBuilder1() { product = new Product(); } ~ConcreatBuilder1() { delete product; } void BuildPartA() { product->Add("部件A"); } void BuildPartB() { product->Add("部件B"); } Product *GetResult() { return product; } }; class ConcreatBuilder2 : public Builder { private: Product *product; public: ConcreatBuilder2() { product = new Product(); } ~ConcreatBuilder2() { delete product; } void BuildPartA() { product->Add("部件X"); } void BuildPartB() { product->Add("部件Y"); } Product *GetResult() { return product; } };
3.写一个Director类来规范建造过程,这个类就是规定了Builder类的步骤哪个是第一步、第二步、第三步 …
class Director // 指挥类-控制建造过程。 { public: void Construct(Builder *builder) { builder->BuildPartA(); builder->BuildPartB(); } };
具体实例完整代码
#include <iostream> #include <list> #include <string> using namespace std; class Product { private: list<string> parts; public: void Add(string part) { parts.push_back(part); } void Show() { for (list<string>::iterator it=parts.begin(); it!=parts.end(); ++it) { cout << *it << endl; } } }; // 建造者类-规范了必要的步骤,因为都是纯虚函数,所以子类必须重写,否则编译不过 class Builder { public: virtual void BuildPartA() = 0; virtual void BuildPartB() = 0; virtual Product *GetResult() = 0; }; class ConcreatBuilder1 : public Builder { private: Product *product; public: ConcreatBuilder1() { product = new Product(); } ~ConcreatBuilder1() { delete product; } void BuildPartA() { product->Add("部件A"); } void BuildPartB() { product->Add("部件B"); } Product *GetResult() { return product; } }; class ConcreatBuilder2 : public Builder { private: Product *product; public: ConcreatBuilder2() { product = new Product(); } ~ConcreatBuilder2() { delete product; } void BuildPartA() { product->Add("部件X"); } void BuildPartB() { product->Add("部件Y"); } Product *GetResult() { return product; } }; class Director // 指挥类-控制建造过程。 { public: void Construct(Builder *builder) { builder->BuildPartA(); builder->BuildPartB(); } }; int main() { Director *director = new Director(); Builder *builder1 = new ConcreatBuilder1(); Builder *builder2 = new ConcreatBuilder2(); director->Construct(builder1); Product *product1 = builder1->GetResult(); product1->Show(); director->Construct(builder2); Product *product2 = builder2->GetResult(); product2->Show(); return 0; }
参考资料
程杰老师的《大话设计模式》
如果对你有帮助的话,记得点赞、收藏,如果有什么遗漏的或者有什么体会,请在评论告诉我,好东西记得分享 ^ _ ^