设计模式之构建器模式

1,目标:将对象的创建和它的表示法分开.
2,实例代码:
#include <iostream>
#include <cassert>
#include <vector>
using namespace std;

class Part
{
public:
    //其一个下标的作用
    enum BPart{ WHEEL,MOUNTAIN,RACE,PNUM };//这里NUM的使用,计数
private:
    BPart id;
    static string partName[PNUM];
public:
    Part(BPart bp):id(bp){}
    friend ostream& operator<<(ostream& os,const Part& bp)
    {
        return os<<partName[bp.id];
    }
};
string Part::partName[PNUM]={ "wheel","mountain","race" };

class Bicycle //相当于Part的向导器
{
    vector<Part*> parts;
public:
    ~Bicycle()
    {
        for( vector<Part*>::iterator ite=parts.begin();ite!=parts.end();ite++ )
            delete *ite;
    }
    void addPart(Part* bp){ parts.push_back(bp); } //自行车添加构件
    friend ostream& operator<<(ostream& os,Bicycle& b)
    {
        os<<"Parts:{ ";
        for(vector<Part*>::iterator ite=b.parts.begin();ite!=b.parts.end();ite++ )
            os<<*(*ite)<<" ";
        return os<<"}";
    }
};

class BicycleBuilder
{
protected:
    Bicycle* product;
public:
    BicycleBuilder(){ product=0; }
    //关键
    void createProduct(){ product=new Bicycle; }
    virtual void buildWheel()=0;
    virtual void buildMountain()=0;
    virtual void buildRace()=0;
    virtual string getBikeName()=0;
    Bicycle* getProduct()
    {
        Bicycle* temp=product;
        product=0;//这里的使用*****
        return temp;
    }
};

class MountainBuilder : public BicycleBuilder
{
public:
    //不同类型的自行车,行为不同
    void buildWheel(){ product->addPart( new Part(Part::WHEEL) ); }
    void buildMountain(){ product->addPart( new Part(Part::MOUNTAIN) ); }
    void buildRace(){};
    string getBikeName(){ return "MountainBike"; }
};

class RaceBuilder : public BicycleBuilder
{
public:
    void buildWheel(){ product->addPart( new Part(Part::WHEEL) ); }
    void buildMountain(){}
    void buildRace(){ product->addPart( new Part(Part::RACE) ); };
    string getBikeName(){ return "RaceBike"; }
};

class BuilderTech//Builder的向导器
{
    BicycleBuilder* builder;
public:
    BuilderTech(){ builder=0; }
    void setBuilder(BicycleBuilder* b){ builder=b; }
    void construct()
    {
        assert(builder);
        builder->createProduct();//这里****
        builder->buildWheel();
        builder->buildMountain();
        builder->buildRace();
        cout<<"Build bike:"<<builder->getBikeName()<<endl;
    }
};

int main()
{
    BicycleBuilder* builder;
    BuilderTech t;

    builder=new MountainBuilder;
    t.setBuilder(builder);
    t.construct();
    cout<<*(builder->getProduct())<<endl;

    builder=new RaceBuilder;
    t.setBuilder(builder);
    t.construct();
    cout<<*(builder->getProduct())<<endl;

    return 0;
}


核心:部件组合成为一个完整产品的算法和部件本身分开了.

你可能感兴趣的:(设计模式,算法,OS)