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; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- PropertyChangeListener简单理解
- 关于指针的一些事情
- 什么是设计模式
- 设计模式之创建型模式 - 特别的变量问题
- 七、设计模式——装饰模式
- 设计模式总结
- 设计模式之创建型模式
- 浅谈设计模式的学习
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题