码迷,mamicode.com
首页 > 编程语言 > 详细

[设计模式]<2>. C++与生成器模式(Builder pattern)

时间:2016-06-15 01:42:28      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

原文地址:

http://www.cnblogs.com/hebaichuanyeah/p/5585957.html

 

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

 

简单例子,构建produce类,需要构建三个部分part1,part2,part3。通过build类去构建它们,并返回。通过director
类调用build对象进行配置。

 

C++代码

#include <iostream>

using namespace std;

class Produce
{
public:
    Produce(){}
    virtual ~Produce(){}

};

class Builder
{
public:
    Builder(){}
    virtual ~Builder(){}

    virtual void BuildPart1(){}
    virtual void BuildPart2(){}
    virtual void BuildPart3(){}
    virtual Produce * GetProduce(){}

};

class ProduceBuilder:public Builder
{
private:
Produce * produce;
public:
    ProduceBuilder(){}

    virtual void BuildPart1()
    {
        produce = new Produce();
        cout<<"bulid part1"<<endl;
        //填充构建part1部分
    }
    virtual void BuildPart2()
    {
        cout<<"bulid part2"<<endl;
        //填充构建part2部分
    }
    virtual void BuildPart3()
    {
        cout<<"bulid part3"<<endl;
        //填充构建part3部分
    }
    virtual Produce * GetProduce()
    {
        return produce;
    }

};

class Director
{
private:
    Builder * bulider;
public:
    Director(Builder * builder)
    {
        bulider = builder;
    }
    void construct()
    {
        bulider->BuildPart1();
        bulider->BuildPart2();
        bulider->BuildPart3();
    }
};
main()
{
    Produce * produce;
    Builder * bulider  = new ProduceBuilder();
    Director * myDirector = new Director(bulider);
    myDirector->construct();
    produce = bulider->GetProduce();
}

 

[设计模式]<2>. C++与生成器模式(Builder pattern)

标签:

原文地址:http://www.cnblogs.com/hebaichuanyeah/p/5585957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!