• 建造者模式


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

    以建造小人为例子,一共需建造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" << '
    '; }
        void buildBody() { std::cout << "build thin body" << '
    '; }
        void buildLeftArm() { std::cout << "build thin left arm" << '
    '; }
        void buildRightArm() { std::cout << "build thin right arm" << '
    '; }
        void buildLeftLeg() { std::cout << "build thin left leg" << '
    '; }
        void buildRightLeg() { std::cout << "build thin right leg" << '
    '; }
    };
    
    class CFatBuilder : public IBuilder
    {
    public:
        CFatBuilder() {}
        ~CFatBuilder() {}
        void buildHead() { std::cout << "build fat head" << '
    '; }
        void buildBody() { std::cout << "build fat body" << '
    '; }
        void buildLeftArm() { std::cout << "build fat left arm" << '
    '; }
        void buildRightArm() { std::cout << "build fat right arm" << '
    '; }
        void buildLeftLeg() { std::cout << "build fat left leg" << '
    '; }
        void buildRightLeg() { std::cout << "build fat right leg" << '
    '; }
    };
    
    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;
    }
  • 相关阅读:
    python+hadoop=?
    Fluentd: The Missing Log Collector
    hadoop streaming 记录
    valgrind备忘
    [hadoop源码阅读][9]mapreduce概论
    GNU Binutils工具
    vim encoding
    [hadoop源码阅读][8]datanodedatanode
    Webdis: HTTP + JSON API for Redis
    gdb 小备注
  • 原文地址:https://www.cnblogs.com/zuofaqi/p/10475596.html
Copyright © 2020-2023  润新知