您的位置:首页 > 编程语言 > C语言/C++

c++设计模式(4)------建造者模式

2015-12-10 21:31 369 查看

建造者模式简介

1)适合的场景:对于对象的创建很复杂,而且对象的创建过程可以任意组合的情况。

2)举例:建造房子,要建造墙壁、窗户、门;而且假设可以以任何顺序来建造,那么这个的情景就适合建造者模式

3)类图的表示:

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
class Home
{
public:
Home()
{}
Home(string wall , string door , string window):m_wall(wall),m_door(door),m_window(window)
{}

public:
string getDoor()
{
return m_door;
}
string getWindow()
{
return m_window;
}
string getWall()
{
return m_wall;
}
void setDoor(string str)
{
m_door = str;
}
void setWindow(string str)
{
m_window = str;
}
void setWall(string str)
{
m_wall = str;
}
private:
string m_wall;
string m_door;
string m_window;

};
//建筑师是控制产品的创建,而且产品的创建比较复杂
class Builder
{
public:

virtual void createWall() = 0;
virtual void createDoor() = 0;
virtual void createWindow() = 0;
};
class Builder_Falt : public Builder
{
public:
Builder_Falt(Home * home):m_home(home)
{

}
virtual void createWall()
{
cout<<"this is creating wall  平方 "<<endl;
cout<<"wall name "<<m_home->getWall()<<endl;
}
virtual void createDoor()
{
cout<<"this is creating door 平方"<<endl;
cout<<"door name "<<m_home->getDoor()<<endl;
}
virtual void createWindow()
{
cout<<"this is creating window 平方"<<endl;
cout<<"window name "<<m_home->getWindow()<<endl;
}
private:
Home * m_home;
};
class Builder_gongyu : public Builder
{
public:
Builder_gongyu(Home * home):m_home(home)
{

}
virtual void createWall()
{
cout<<"this is creating wall gongyu "<<endl;
cout<<"wall name "<<m_home->getWall()<<endl;
}
virtual void createDoor()
{
cout<<"this is creating door  gongyu"<<endl;
cout<<"door name "<<m_home->getDoor()<<endl;
}
virtual void createWindow()
{
cout<<"this is creating window gongyu "<<endl;
cout<<"window name "<<m_home->getWindow()<<endl;
}
private:
Home * m_home;
};
//设计师控制产品的建造逻辑
class Designer
{
public:
Designer(Builder* builde)
{
m_builder = builde;
}
void createHome()
{
m_builder->createDoor();
m_builder->createWindow();
m_builder->createWall();
}
private:
Builder* m_builder;
};

int main()
{

Home * home = new Home;
home->setDoor("门");
home->setWindow("窗户");
home->setWall("墙壁");
Builder* bt = new Builder_gongyu(home);
Designer * ds = new Designer(bt);
ds->createHome();
cout<<"hello world"<<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息