标签:
原文地址:
http://www.cnblogs.com/hebaichuanyeah/p/5585957.html
当构建一个复杂对象时,将构建过程与表示分离。使得同样的过程创建不同的对象。
简单例子,构建produce类,需要构建三个部分part1,part2,part3。通过build类去构建它们,并返回。通过director
类调用build对象进行配置。
C++代码
#include <iostream> using namespace std; class Produce { public: Produce(){} virtual ~Produce(){} }; class Builder { public: Builder(){} virtual ~Builder(){} virtual void BuildPart1(){} virtual void BuildPart2(){} virtual void BuildPart3(){} virtual Produce * GetProduce(){} }; class ProduceBuilder:public Builder { private: Produce * produce; public: ProduceBuilder(){} virtual void BuildPart1() { produce = new Produce(); cout<<"bulid part1"<<endl; //填充构建part1部分 } virtual void BuildPart2() { cout<<"bulid part2"<<endl; //填充构建part2部分 } virtual void BuildPart3() { cout<<"bulid part3"<<endl; //填充构建part3部分 } virtual Produce * GetProduce() { return produce; } }; class Director { private: Builder * bulider; public: Director(Builder * builder) { bulider = builder; } void construct() { bulider->BuildPart1(); bulider->BuildPart2(); bulider->BuildPart3(); } }; main() { Produce * produce; Builder * bulider = new ProduceBuilder(); Director * myDirector = new Director(bulider); myDirector->construct(); produce = bulider->GetProduce(); }
[设计模式]<2>. C++与生成器模式(Builder pattern)
标签:
原文地址:http://www.cnblogs.com/hebaichuanyeah/p/5585957.html