设计模式-创建-Builder(建造者)模式
目的:当对象的构造很复杂,分为好几部分的时候,可以用建造者模式来处理
把一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。.
通常把一个复杂对象构建分为几个部分 BuildPartA B C…..
Builder模式有以下几个角色
Builder: 规定一些接口
ConCreateBuilder:Builder 的实现
Director:负责具体的装配调用
版本1:
class Procudt { public: void initPartA(){} void initPartB(){} void Print(){ cout << __FUNCTION__ << endl; } }; class Builder { public: virtual void BuildPartA() = 0; virtual void BuildPartB() = 0; virtual Procudt* GetProduct() = 0; }; class ConCreateBuilder :public Builder { Procudt *product; public: virtual void BuildPartA()override { cout << __FUNCTION__ << endl; product->initPartA(); } virtual void BuildPartB()override { cout << __FUNCTION__ << endl; product->initPartB(); } Procudt * GetProduct()override { return product; } }; class Director { public: Director(Builder *builder) { _builder = builder; } void Construct() { _builder->BuildPartA(); _builder->BuildPartB(); } Builder* _builder; }; int main(int argc, char *argv[]) { ConCreateBuilder* builder = new ConCreateBuilder; Director* director = new Director(builder); director->Construct(); builder->GetProduct()->Print(); system("pause"); return 0; }
版本2:
class Director { public: Builder* Construct(Builder *_builder) { _builder->BuildPartA(); _builder->BuildPartB(); return _builder; } }; int main(int argc, char *argv[]) { ConCreateBuilder* builder = ; Director* director = new Director(); Builder *builder = director->Construct(new ConCreateBuilder); builder->GetProduct()->Print(); system("pause"); return 0; } //Director 只是一个 组装