zoukankan      html  css  js  c++  java
  • 设计模式 --> (4)建造者模式

    建造者(Builder)模式

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

      建造者模式包含一个抽象的Builder类,还有它的若干子类——ConcreteBuilder,关键是看指挥官Director,Director里面的方法Construct()其实包含了Builder指针或引用的形参,由客户端传入某个 ConcreateBuilder对象。由多态性可知,客户端传进来的ConcreteBuilder是谁,就调用谁的方法。

    优点:

      1.隔离了构建的步骤和具体的实现,为产品的具体实现提供了灵活度。

      2.封装和抽象了每个步骤的实现,实现了依赖倒转原则。

      3.封装了具体的步骤,减少了代码的冗余。

    缺点:

      1.要求构建产品的步骤(算法)是不能剧烈变化的,最好是不变的,这样就影响了灵活度。

    具体代码:

    // 建造者
    class Builder
    {
    public:
        virtual void buildPart1() = 0;
        virtual void buildPart2() = 0;
    };
    
    //具体建造者1
    class ConcreteBuilder1: public Builder
    {
    public:
        void buildPart1() { cout << "用A构造第一部分" << endl; }
        void buildPart2() { cout << "用B构造第二部分" << endl; }
    };
    
    //具体建造者2
    class ConcreteBuilder2: public Builder
    {
    public:
        void buildPart1() { cout << "用X构造第一部分" << endl; }
        void buildPart2() { cout << "用Y构造第二部分" << endl; }
    };
    
    // 指挥者,注意其方法的参数是抽象建造者的指针
    class Director
    {
    private:  
        Builder *m_pBuilder;  
    public:
        Director(Builder *builder) { m_pBuilder = builder; }  
        void build()
        {
            m_pBuilder->buildPart1();
            m_pBuilder->buildPart2();
        }
    };

    客户使用方法:

    int main()
    {
        Director d(new ConcreteBuilder1());
        d.build();
        return 0;
    }

    参考:http://blog.csdn.net/wuzhekai1985

  • 相关阅读:
    POJ3320 Jessica's Reading Problem
    POJ3320 Jessica's Reading Problem
    CodeForces 813B The Golden Age
    CodeForces 813B The Golden Age
    An impassioned circulation of affection CodeForces
    An impassioned circulation of affection CodeForces
    Codeforces Round #444 (Div. 2) B. Cubes for Masha
    2013=7=21 进制转换
    2013=7=15
    2013=7=14
  • 原文地址:https://www.cnblogs.com/jeakeven/p/4926318.html
Copyright © 2011-2022 走看看