欢迎来到天天文库
浏览记录
ID:36584929
大小:188.00 KB
页数:8页
时间:2019-05-12
《常见设计模式的解析和实现(C)之九Decorator模式》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、常见设计模式的解析和实现(C++)之九-Decorator模式作用:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。UML结构图:抽象基类:1)Component:定义一个对象接口,可以为这个接口动态的添加职责.2)Decorator:维持一个指向Component的指针,并且有一个和Component一致的接口函数.接口函数:1)Component::Operation:这个接口函数由Component声明,因此Component的派生类都需要实现,可以在这个接口函数的基础上给它动态添加职责.解析:Decorator的派生类可以为Conc
2、reateComponent类的对象动态的添加职责,或者可以这么说:Decorator的派生类装饰ConcreateComponent类的对象.具体是这么实现的,首先初始化一个ConcreateComponent类的对象(被装饰者),采用这个对象去生成一个Decorator对象(装饰者),之后对Operation函数的调用则是对这个Decorator对象成员函数的多态调用.这里的实现要点是Decorator类和ConcreateComponent类都继承自Component,从而两者的接口函数是一致的;其次,Decorator维护了一个指向Component的指针,从而可以实现对Comp
3、onent::Operation函数的动态调用.实现:1)Decorator.h/**//********************************************************************created:2006/07/20filename:Decorator.hauthor:李创http://www.cppblog.com/converse/purpose:Decorator模式的演示代码*********************************************************************/#ifndefDECO
4、RATOR_H#defineDECORATOR_H//抽象基类,定义一个对象接口,可以为这个接口动态的添加职责.classComponent{public:Component(){}virtual~Component(){}//纯虚函数,由派生类实现virtualvoidOperation()=0;};//抽象基类,维护一个指向Component对象的指针classDecorator:publicComponent{public:Decorator(Component*pComponent):m_pComponent(pComponent){}virtual~Decorator();pr
5、otected:Component*m_pComponent;};//派生自Component,在这里表示需要给它动态添加职责的类classConcreateComponent:publicComponent{public:ConcreateComponent(){}virtual~ConcreateComponent(){}virtualvoidOperation();};//派生自Decorator,这里代表为ConcreateComponent动态添加职责的类classConcreateDecorator:publicDecorator{public:ConcreateDecora
6、tor(Component*pComponent):Decorator(pComponent){}virtual~ConcreateDecorator(){}virtualvoidOperation();private:voidAddedBehavior();};#endif2)Decorator.cpp/**//********************************************************************created:2006/07/20filename:Decorator.cppauthor:李创http://www.cppblog.com
7、/converse/purpose:Decorator模式的演示代码*********************************************************************/#include"Decorator.h"#includeDecorator::~Decorator(){deletem_pComponent;m_pComponent=NULL;}voidConcreate
此文档下载收益归作者所有