现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式6:建造者模式【创建型】

2013-02-23 12:07 工业·编程 ⁄ 共 1612字 ⁄ 字号 暂无评论

#include <iostream>
#include <vector>
using namespace std;

//
class CProduct
{
public:
    CProduct() { }

    void Add(char *str) { m_pVec.push_back(str); }

    void ShowProduct()
    {
        vector<char*>::iterator ite = m_pVec.begin();
        for (; m_pVec.end() != ite; ite++)
        {
            cout<<*ite<<endl;
        }
    }
private:
    vector<char*> m_pVec;
};
//
struct IBuilder
{
public:
    IBuilder() { m_pProduct = new CProduct; }
    virtual ~IBuilder()
    {
        if(m_pProduct)
        {
            delete m_pProduct;
            m_pProduct = NULL;
        }
    }

    virtual void BuildStep1() = 0;
    virtual void BuildStep2() = 0;
    virtual void BuildStep3() = 0;

    CProduct* GetProduct() { return m_pProduct; }

protected:
    CProduct *m_pProduct;
};

class CBuilderA : public IBuilder
{
public:
    virtual ~CBuilderA() { }

    virtual void BuildStep1() { m_pProduct->Add("A Step 1"); }
    virtual void BuildStep2() { m_pProduct->Add("A Step 2");  }
    virtual void BuildStep3() { m_pProduct->Add("A Step 3");  }
};

class CBuilderB : public IBuilder
{
public:
    virtual ~CBuilderB() { }

    virtual void BuildStep1() { m_pProduct->Add("B Step 1"); }
    virtual void BuildStep2() { m_pProduct->Add("B Step 2");  }
    virtual void BuildStep3() { m_pProduct->Add("B Step 3");  }
};

//
class CDirector
{
public:
    CDirector() { }
    ~CDirector() { }

    void Produce(IBuilder *pBuilder)
    {
        pBuilder->BuildStep1();
        pBuilder->BuildStep2();
        pBuilder->BuildStep3();
    }
};

//
void main()
{
    CDirector director;

    //
    CBuilderA builderA;
    director.Produce(&builderA);

    CProduct *pProductA = builderA.GetProduct();
    pProductA->ShowProduct();

    //
    CBuilderB builderB;
    director.Produce(&builderB);
   
    CProduct *pProductB = builderB.GetProduct();
    pProductB->ShowProduct();
}

给我留言

留言无头像?