Builder模式

2017-09-12  本文已影响14人  第八区

剖析

创建型的设计模式。关注对象创建的过程

与工厂模式的区别。

工厂和Builder应该怎么取选择?

当一个对象创建的过程比较简单,比如:手机,在发布时候型号功能颜色都已经确定,这是我们只需要一个手机工厂给我们创建即可。当一个对象产品比较复杂,自定义属性的比较多,同时创建的流程也比较复杂,比如组装电脑。每个配件都可以自己选择,而且组装的过程也很重要,这时候用Builder就比较合适

元素

build.png

示例

问题

一个人需要在一块地上盖一栋别墅。

抽象产品
class Hourse {
protected:
    int size;
    int height;
    int level;
    string name;
public:
    Hourse(int size, int height, int level, string name) {
        this->size = size;
        this->height = height;
        this->level = level;
        this->name = name;
    }
    virtual void show()const = 0;
};
具体产品
class CottageHourse :public Hourse {
private :
    double price;
public:
    CottageHourse(int size, int height, int level, string name, double price) :Hourse(size, height, level, name) {
        this->price = price;
    }
    void show() const {
        cout << name.c_str() << " 规格" << endl;
        cout << "大小:" << size << endl;
        cout << "高度:" << height << endl;
        cout << "级别:" << level << endl;
        cout << "售价:" << price<<"万" << endl;
    }
};
抽象构造者
class HourseBuild {
public:
    virtual int makeFoundation(int size)=0;

    virtual int makeWall(int height)=0;

    virtual int makeDecorate(int level)=0;
};
具体构造者
class CottageHourseBuild :public HourseBuild {
    int makeFoundation(int size) {
        return size;
     }

    int makeWall(int height) {
        return height;
     }

    int makeDecorate(int level) {
        return level;
    }
};
抽象指挥者
class Director {
protected:
    HourseBuild* hourseBuild;
public:
    Director(HourseBuild* build) {
        this->hourseBuild = build;
    }
    virtual Hourse* createHourse() = 0;
    HourseBuild* getBuild() {
        return hourseBuild;
    }
};
具体指挥者
class CottageDirector :public Director {
public:
    CottageDirector(HourseBuild* build) :Director(build){

    }
     Hourse* createHourse() {
         int sizeRes = getBuild()->makeFoundation(100);
         int heightRes = Director::hourseBuild->makeWall(10);
         int levelRes = Director::hourseBuild->makeDecorate(5);
         return new CottageHourse(sizeRes, heightRes, levelRes, "海景别墅", 998);
    }
};
测试调用
int main()
{
    HourseBuild * build = new CottageHourseBuild();
    Director *director = new CottageDirector(build);
    Hourse *hourse = director->createHourse();
    hourse->show();
    delete hourse;
    delete director;
    delete build;
    return 0;
}

结果


build_res.png
上一篇下一篇

猜你喜欢

热点阅读