大话设计模式学习(一)----装饰模式
2016-03-16 16:34
316 查看
大话设计模式学习(三)—-装饰模式C++实现
前面还有简单工厂模式和策略模式,今天先记录装饰模式一、装饰模式介绍
注意这里面涉及到的设计原则
开放-封闭原则(OCP)
Software entities(classes,modules,functions etc) should open for extension ,but close for modification.
什么意思呢?
所谓开放封闭原则就是软件实体应该对扩展开放,而对修改封闭。开放封闭原则是所有面向对象原则的核心。软件设计本身所追求的目标就是封装变化,降低耦合,而开放封闭原则正是对这一目标的最直接体现。
开放封闭原则主要体现在两个方面:
对扩展开放,意味着有新的需求或变化时,可以对现有代码进行扩展,以适应新的情况。
对修改封闭,意味着类一旦设计完成,就可以独立其工作,而不要对类尽任何修改。
二、装饰模式C++实现
环境 win764位 VS2013场景:小菜穿衣服
类结构实现代码
#include <iostream> using namespace std; class person { public: person(string setName) { this->name = setName; } person() {} virtual void show() { printf("%s%s\n", "装扮的", name); } private: string name; }; class clothes : public person { public: void decorate(person *setComponent) { this->component = setComponent; } void show() { if (component) { component->show(); } } private: person *component = NULL; }; class TShirts:public clothes { public: void show() { cout << "大T恤" << endl; clothes::show(); return; } private: }; class bigTrouser:public clothes { public: void show() { cout << "垮裤" << endl; clothes::show(); return; } private: }; class shoes : public clothes { public: void show() { cout << "球鞋" << endl; clothes::show(); return; } };
测试函数
void testDecorator() { person *xc = new person("小菜"); TShirts *tx = new TShirts; bigTrouser *kk = new bigTrouser; shoes *qiuxie = new shoes; tx->decorate(xc); kk->decorate(tx); qiuxie->decorate(kk); qiuxie->show(); }
注意在person类的实现中,需要加上person(){},这个空的构造函数,不然会出错
所有设计模式实现的C++代码我都会传到github上面,之后给出地址
git地址如下
设计模式C++实现代码(不断更新中)
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- PropertyChangeListener简单理解
- 关于指针的一些事情
- 什么是设计模式
- 设计模式之创建型模式 - 特别的变量问题
- 七、设计模式——装饰模式
- 设计模式总结
- 设计模式之创建型模式
- 浅谈设计模式的学习
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Ruby设计模式编程之适配器模式实战攻略
- 实例讲解Ruby使用设计模式中的装饰器模式的方法
- 设计模式中的模板方法模式在Ruby中的应用实例两则
- 实例解析Ruby设计模式编程中Strategy策略模式的使用
- Ruby中使用设计模式中的简单工厂模式和工厂方法模式
- Ruby使用设计模式中的代理模式与装饰模式的代码实例
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- 详解组合模式的结构及其在Ruby设计模式编程中的运用