概念:
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;
}