Design Pattern之装饰模式
2018-02-14 19:49
183 查看
装饰模式(Decorator),动态地给一个对象添加额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式是为已有功能动态添加更多功能的一种方式,当系统需要更新的时候,是向旧的类中添加新的代码,这些新加的代码通常装饰了原有类的核心职责或主要行为。如果在已有的类中添加新的字段、新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为需要。装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择、按顺序使用装饰。装饰模式的优点就是把类中的装饰功能从类中搬移出去,这样可以简化原有的类。
下面是装饰模式的UML图:
根据大话设计模式上的例子,利用C++对原有代码进行重写。代码如下所示:
对于重复的类这里就不再一一列举了。
最后运行结果如下:
装饰模式是为已有功能动态添加更多功能的一种方式,当系统需要更新的时候,是向旧的类中添加新的代码,这些新加的代码通常装饰了原有类的核心职责或主要行为。如果在已有的类中添加新的字段、新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为需要。装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择、按顺序使用装饰。装饰模式的优点就是把类中的装饰功能从类中搬移出去,这样可以简化原有的类。
下面是装饰模式的UML图:
根据大话设计模式上的例子,利用C++对原有代码进行重写。代码如下所示:
//Person.h Person抽象父类 #ifndef __PERSON_H #define __PERSON_H #include <stdio.h> #include <string.h> const int MAX_NAME_LEN = 256; class Person { public: virtual ~Person() {} virtual void Show() = 0; protected: char m_szName[MAX_NAME_LEN]; }; #endif // !__PERSON_H
//Professor.h 继承Person类 #ifndef __PROFESSOR_H #define __PROFESSOR_H #include "Person.h" class Professor : public Person { public: Professor( char* szName) { memset(m_szName, 0, MAX_NAME_LEN); if (NULL == szName) { printf("szName = NULL\n"); memcpy(m_szName, "Professor", MAX_NAME_LEN); } else { memcpy(m_szName, szName, MAX_NAME_LEN); } } ~Professor() {} virtual void Show() { printf("Show Professor:%s\n", m_szName); } }; #endif // !__PROFESSOR_H
//Decorator.h 装饰类 继承Person类 #ifndef __DECORATOR #define __DECORATOR #include "Person.h" class Decorator : public Person { public: Decorator() { m_pPerson = NULL; } ~Decorator(){ } void Decorate(Person *person) { if (person != NULL) { m_pPerson = person; } } void Show() { if (m_pPerson) { m_pPerson->Show(); } } private: Person *m_pPerson; }; #endif
//Sneakers .h 继承Decorator类 #ifndef __SNEAKERS_H #define __SNEAKERS_H #include "Decorator.h" class Sneakers : public Decorator { public: Sneakers() {} ~Sneakers() {} void Show() { printf("球鞋\n"); Decorator::Show(); } }; #endif
对于重复的类这里就不再一一列举了。
最后运行结果如下:
相关文章推荐
- Design Pattern【7】装饰模式
- 装饰设计模式(decorator design pattern)
- Design Pattern - 装饰模式
- Design Pattern学习笔记 --- Bridge(桥接)模式
- JavaSE第九十三讲:装饰模式深入详解
- 设计模式 - 结构型模式 - 装饰模式
- J2SE中带缓冲的字符流与装饰设计模式
- 装饰模式
- c++ 装饰模式(decorate)
- Design Pattern—— static proxy pattern 静态代理模式
- 装饰设计模式
- Java基础-装饰设计模式、装饰与继承的区别
- (C++设计模式) ------Decorator装饰模式-- 结构型模式
- [设计模式]-装饰器模式(Decorator)
- Java 装饰模式 io流
- java设计模式之装饰模式
- 黑马程序员-装饰设计模式
- Python设计模式(4)-装饰模式
- Design Pattern_Factory Method(工厂模式)
- 设计模式之装饰模式(Decorator)