建造者模式 Builder Mode
创建者模式是创建型模式中最负责的一个设计模式了,创建者负责构建一个对象的各个部分,并且完成组装的过程,我们可以这么理解创建
者模式,创建者模式类似与一个步骤基本固定,但是每个步骤中的具体形式却又可以变化的这类对象的创建。
#include<iostream> using namespace std; class Builder{ public: virtual void buildHead() = 0; virtual void buildHand() = 0; virtual void buildLeg() = 0; virtual void show() = 0; }; class ThinPerson:public Builder{ public: void buildHead(){ cout<<"build ThinPerson head"<<endl; } void buildHand(){ cout<<"build ThinPerson hand"<<endl; } void buildLeg(){ cout<<"build ThinPerson leg"<<endl; } void show(){ cout<<"thinperson"<<endl; } }; class FatPerson:public Builder{ public: void buildHead(){ cout<<"build FatPerson head"<<endl; } void buildHand(){ cout<<"build FatPerson hand"<<endl; } void buildLeg(){ cout<<"build FatPerson leg"<<endl; } void show(){ cout<<"fatperson"<<endl; } }; class Director{ public: Director(Builder * builder){ m_builder = builder; } void construct(){ m_builder->buildHead(); m_builder->buildHand(); m_builder->buildLeg(); } Builder * getProduct(){ return m_builder; } private: Builder * m_builder; }; int main(int argc, char* argv[]) { Builder * pbuilder = new FatPerson(); Director * pdirector = new Director(pbuilder); pdirector->construct(); //之前在new FatPerson中new了,在这会进行具体构造 pdirector->getProduct()->show(); //这是和pbuilder一样的,指向同一对象 delete pbuilder; delete pdirector; return 0; }