建造者模式

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

以建造小人为例子,一共需建造6个部分,头部、身体、左右手、左右脚。与工厂模式不同,建造者模式是在导向者的控制下一步一步构造产品的。建造小人就是在控制下一步步构造出来的。创建者模式可以能更精细的控制构建过程,从而能更精细的控制所得产品的内部结构。

UML

 

#include <iostream>

class IBuilder
{
public:
    IBuilder() {}
    virtual ~IBuilder() {}
    virtual void buildHead() = 0;
    virtual void buildBody() = 0;
    virtual void buildLeftArm() = 0;
    virtual void buildRightArm() = 0;
    virtual void buildLeftLeg() = 0;
    virtual void buildRightLeg() = 0;
};

class CThinBuilder : public IBuilder
{
public:
    CThinBuilder() {}
    ~CThinBuilder() {}
    void buildHead() { std::cout << "build thin head" << '\n'; }
    void buildBody() { std::cout << "build thin body" << '\n'; }
    void buildLeftArm() { std::cout << "build thin left arm" << '\n'; }
    void buildRightArm() { std::cout << "build thin right arm" << '\n'; }
    void buildLeftLeg() { std::cout << "build thin left leg" << '\n'; }
    void buildRightLeg() { std::cout << "build thin right leg" << '\n'; }
};

class CFatBuilder : public IBuilder
{
public:
    CFatBuilder() {}
    ~CFatBuilder() {}
    void buildHead() { std::cout << "build fat head" << '\n'; }
    void buildBody() { std::cout << "build fat body" << '\n'; }
    void buildLeftArm() { std::cout << "build fat left arm" << '\n'; }
    void buildRightArm() { std::cout << "build fat right arm" << '\n'; }
    void buildLeftLeg() { std::cout << "build fat left leg" << '\n'; }
    void buildRightLeg() { std::cout << "build fat right leg" << '\n'; }
};

class CDirector
{
public:
    CDirector(IBuilder* pBuilder) : m_pBuilder(pBuilder) {}
    ~CDirector() {}

    void create()
    {
        m_pBuilder->buildHead();
        m_pBuilder->buildBody();
        m_pBuilder->buildLeftArm();
        m_pBuilder->buildRightArm();
        m_pBuilder->buildLeftLeg();
        m_pBuilder->buildRightLeg();
    }
    
private:
    IBuilder* m_pBuilder;
};


int main()
{
    IBuilder* builder = new CFatBuilder();
    CDirector director(builder);

    director.create();

    delete builder;

    return 0;
}

 

posted @ 2019-03-05 11:25  二狗啸地  阅读(93)  评论(0编辑  收藏  举报