设计模式(三)之建造者模式(Builder) C++实现

作用:

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

解析:

Builder模式是基于这样的一个情况:一个对象可能有不同的组成部分,这几个部分的不同的创建对象会有不同的表示,但是各个部分之间装配的方式是一致的。

Builder.h

// 抽象基类AbstractProductA,代表产品A的抽象
class Builder
{
public:
    Builder(){}
    virtual ~Builder(){}
    virtual void BuildPartA() = 0;
    virtual void BuildPartB() = 0;
};

class ConcreateBuilder1
    : public Builder
{
public:
    ConcreateBuilder1(){}
    virtual ~ConcreateBuilder1(){}
    virtual void BuildPartA();
    virtual void BuildPartB();
};

class ConcreateBuilder2
    : public Builder
{
public:
    ConcreateBuilder2(){}
    virtual ~ConcreateBuilder2(){}
    virtual void BuildPartA();
    virtual void BuildPartB();
};

class Director
{
public:
    Director(Builder * pBuilder) : m_pBuilder(pBuilder){}
    ~Director();
    void Construct();
private:
    Builder * m_pBuilder;
};

Builder.cpp

#include "Builder.h"
#include 
using namespace std;
void ConcreateBuilder1::BuildPartA()
{
    cout << "ConcreateBuilder1 Step1:Build PartA..." << endl;
}

void ConcreateBuilder1::BuildPartB()
{
    cout << "ConcreateBuilder1 Step2:Build PartB..." << endl;
}

void ConcreateBuilder2::BuildPartA()
{
    cout << "ConcreateBuilder2 Step1:Build PartA..." << endl;
}

void ConcreateBuilder2::BuildPartB()
{
    cout << "ConcreateBuilder2 Step2:Build PartB..." << endl;
}

Director::~Director()
{
    delete m_pBuilder;
    m_pBuilder = NULL;
}

void Director::Construct()
{
    m_pBuilder->BuildPartA();
    m_pBuilder->BuildPartB();
}

main.cpp

#include "AbstractFactory.h"
int main(int argc, char* argv[])
{
    Builder *builder1 = new ConcreateBuilder1();
    Builder *builder2 = new ConcreateBuilder2();

    Director *director = new Director(builder1);
    director->Construct();
    delete director;

    director = new Director(builder2);
    director->Construct();
    delete director;
    return 0;
}

你可能感兴趣的:(设计模式,设计模式,建造者模式,c++)