Chinaunix首页 | 论坛 | 博客
  • 博客访问: 41377
  • 博文数量: 17
  • 博客积分: 1432
  • 博客等级: 上尉
  • 技术积分: 165
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-27 09:38
文章分类

全部博文(17)

文章存档

2011年(1)

2009年(16)

最近访客

分类: C/C++

2009-02-24 17:35:25

#include <string>
#include <iostream>
#include <list>
using namespace std;
using std::list;

class Product
{
private:
    list<string> parts;

public:
    virtual void Add(string part)
    {
        parts.push_back(part);
    }

    virtual void Show()
    {
        cout<<"\n产品 创建 -----"<<endl;
        list<string>::iterator list_it;
        for(list_it = parts.begin();list_it != parts.end();list_it++)
        {
            cout<<*list_it<<endl;
        }
    }
};

class Builder
{
public:
    virtual void BuildPartA() = 0;
    virtual void BuildPartB() = 0;
    virtual Product* GetResult() = 0;
};

class ConcreateBuilder1 : public Builder
{
private:
    Product* m_product;

public:
    ConcreateBuilder1()
    {
        m_product = new Product();
    }

    virtual void BuildPartA()
    {
        m_product->Add("部件A");
    }

    virtual void BuildPartB()
    {
        m_product->Add("部件B");
    }

    virtual Product* GetResult()
    {
        return m_product;
    }
};

class ConcreateBuilder2 : public Builder
{
private:
    Product* m_product;

public:
    ConcreateBuilder2()
    {
        m_product = new Product();
    }

    virtual void BuildPartA()
    {
        m_product->Add("部件X");
    }

    virtual void BuildPartB()
    {
        m_product->Add("部件Y");
    }

    virtual Product* GetResult()
    {
        return m_product;
    }
};

class Director
{
public:
    void Construct(Builder* builder)
    {
        builder->BuildPartA();
        builder->BuildPartB();
    }
};

int main(void)
{
    Director* director = new Director();
    Builder* b1 = (Builder*)new ConcreateBuilder1();
    Builder* b2 = (Builder*)new ConcreateBuilder2();

    director->Construct(b1);
    Product* p1 = b1->GetResult();
    p1->Show();

    director->Construct(b2);
    Product* p2 = b2->GetResult();
    p2->Show();
};

阅读(537) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~