设计模式之建造者(builder)模式
原创
©著作权归作者所有:来自51CTO博客作者chenchao40322的原创作品,请联系作者获取转载授权,否则将追究法律责任
建造者模式把一个复杂的对象的与他的表示分离,使得同样的构造过程可以构建不同的表示(大话设
计模式)。它把对象的各个组件的组装隐藏起来,对外提供一个组装方法,并对外提供一个对象表现
的抽象接口,调用者通过实现此表现抽象接口来实现多种对象的表现,然后调用组装方法来组装出目
标表对象。
代码如下:
//零部件的基类,外部调用者通过实现此接口来表现各个零部件 class PersonBuilder { public: PersonBuilder(){}; virtual ~PersonBuilder(){}; virtual void BuildHead()=0; virtual void BuildBody()=0; virtual void BuildArmLeft()=0; virtual void BuildArmRight()=0; virtual void BuildLegLeft()=0; virtual void BuildLegRight()=0; }; |
//组件组装类,外部通过调用此类的组装方法 CreatePerson来组装出对象。 class PersonDirector { private: PersonBuilder* _pPersonBuilder; public: PersonDirector():_pPersonBuilder(0){}; PersonDirector(PersonBuilder* pPersonBuilder):_pPersonBuilder(pPersonBuilder){}; ~PersonDirector(); void CreatePerson(); }; | PersonDirector::~PersonDirector() { if(_pPersonBuilder!=0) delete _pPersonBuilder; } void PersonDirector::CreatePerson() { _pPersonBuilder->BuildHead(); _pPersonBuilder->BuildBody(); _pPersonBuilder->BuildArmLeft(); _pPersonBuilder->BuildArmRight(); _pPersonBuilder->BuildLegLeft(); _pPersonBuilder->BuildLegRight(); } |
//调用者实现的一个组件的表现 class PersonFatBuilder : public PersonBuilder { public: PersonFatBuilder(){}; ~PersonFatBuilder(){}; void BuildHead(); void BuildBody(); void BuildArmLeft(); void BuildArmRight(); void BuildLegLeft(); void BuildLegRight(); }; | void PersonFatBuilder::BuildHead() { std::cout<<"胖头"<<std::endl; } void PersonFatBuilder::BuildBody() { std::cout<<"胖身子"<<std::endl; } void PersonFatBuilder::BuildArmLeft() { std::cout<<"胖左手"<<std::endl; } void PersonFatBuilder::BuildArmRight() { std::cout<<"胖右手"<<std::endl; } void PersonFatBuilder::BuildLegLeft() { std::cout<<"胖左腿"<<std::endl; } void PersonFatBuilder::BuildLegRight() { std::cout<<"胖右腿"<<std::endl; } |
//调用者的调用代码。 int main() { PersonDirector* pPersonDirector=new PersonDirector(new PersonFatBuilder); pPersonDirector->CreatePerson(); return 0; } |