建造者模式

概念:
Bulider模式也叫做建造者模式或者生成器模式。
Bulider模式是一种对象创建型模式,用来隐藏复合对象的创建过程,他把符合对象的创建过程加以抽象,通过子类继承和重载的方式,动态的创建具有复合属性的对象。
对象的创建:Bulider模式是为对象的创建而设计的模式,创建的是一个复合对象;被创建的对象为具有一个复合属性的复合对象,关注对象创建的各部分创建过程,不同的生成器对对象的属性有不同的创建方法。
结构图:
这里写图片描述
需求:
现有各种类型的房子比如:别墅、公寓、写字楼等。
对于不同的房子,有不同的工程队,即:别墅工程队、公寓工程队….
设计师通过控制建造提供房子的建造过程,建造出房子。
实现:
抽象房子:

class House{
private:
    string wall;
    string door;
    string window;
public:
    void setWall(string wall){
        this->wall = wall;
        cout << wall << "建造完毕" << endl;
    }
    void setDoor(string door){
        this->door = door;
        cout << door << "建造完毕" << endl;
    }
    void setwindow(string window){
        this->window = window;
        cout << window << "建造完毕" << endl;
    }
};

工程队基类

class Bulider{
protected:
    House *h;
public:
    Bulider(){
        h = new House();
    }
    virtual void BulidWall() = 0;
    virtual void BulidDoor() = 0;
    virtual void BulidWindow() = 0;
    House* getHouse(){
        return h;
    }
    virtual ~Bulider(){}
};

公寓工程队

class FlatBulider :public Bulider{
public:
    void BulidWall(){
        h->setDoor("Flat Wall");
    }
    void BulidDoor(){
        h->setDoor("Flat Door");
    }
    void BulidWindow(){
        h->setwindow("Flat Window");
    }
};

别墅工程队

class VillaBulider :public Bulider{
public:
    void BulidWall(){
        h->setDoor("Villa Wall");
    }
    void BulidDoor(){
        h->setDoor("Villa Door");
    }
    void BulidWindow(){
        h->setwindow("Villa Window");
    }
};

设计师

class Director{
private:
    Bulider *bulider;
public:
    Director(Bulider *bulider){
        this->bulider = bulider;
    }
    void Construct(){
        bulider->BulidWall();   
        bulider->BulidDoor();
        bulider->BulidWindow();
    }
};

客户端:

int main(void){
    //创建一个别墅工程队
    VillaBulider *v = new VillaBulider();
    //设计师设计别墅
    Director *d = new Director(v);
    //设计师指挥工程队干活
    d->Construct();
    House *h = v->getHouse();
    delete v;
    delete d;
    delete h;
    system("pause");
    return 0;
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值