Decorator模式
来源:互联网 发布:python popen函数 编辑:程序博客网 时间:2024/05/29 19:31
Decorator模式
在开发过程中,有时会遇到需要向已经定义好的类添加新功能的需求,这时候通常的做法就是定义一个新类,继承这个类,在新类中添加新功能.
采用继承的方式来实现,在使用时,我们经常使用父类的指针或引用通过多态技术来调用子类的接口,但这样就会遇到一个问题:再向子类添加方法时,也需要向父类添加方法,否则通过父类指针或引用就调用不到这个方法.所以Decorator模式没有采用继承来实现,而是采用组合的方式来实现.类结构如下图所示:
类ConcreteComponent和类Decorator有相同的接口,所以都继承自Component.在Decorator中,有一个指向Component的指针(引用),通过这个指针来调用ConcreteComponent中的函数Operation.
下面是实现:
//Decorator.h
//Decorator.h#ifndef _DECORATOR_H_#define _DECORATOR_H_class Component{public: virtual ~Component(); virtual void Operation();protected: Component();};class ConcreteComponent :public Component{public: ConcreteComponent(); ~ConcreteComponent(); void Operation();};class Decorator :public Component{public: Decorator(Component* com); virtual ~Decorator(); void Operation();protected: Component* _com;};class ConcreteDecorator :public Decorator{public: ConcreteDecorator(Component* com); ~ConcreteDecorator(); void Operation(); void AddedBehavior();};#endif
//Decorator.cpp
//Decorator.cpp#include"Decorator.h"#include<iostream>Component::~Component(){}void Component::Operation(){}Component::Component(){}ConcreteComponent::ConcreteComponent(){}ConcreteComponent::~ConcreteComponent(){}void ConcreteComponent::Operation(){ std::cout << "ConcreteComponent operation" << std::endl;}Decorator::Decorator(Component* com){ _com = com;}Decorator::~Decorator(){ delete _com;}void Decorator::Operation(){}ConcreteDecorator::ConcreteDecorator(Component* com) :Decorator(com){}ConcreteDecorator::~ConcreteDecorator(){}void ConcreteDecorator::AddedBehavior(){ std::cout << "ConcreteDecorator::AddedBehavior..." << std::endl;}void ConcreteDecorator::Operation(){ _com->Operation(); AddedBehavior();}
//main.cpp
//main.cpp#include"Decorator.h"int main(){ Component* com = new ConcreteComponent(); Decorator* dec = new ConcreteDecorator(com); dec->Operation(); delete dec; return 0;}
0 0
- Decorator模式
- Decorator模式
- decorator模式
- Decorator模式
- Decorator模式
- Decorator模式
- Decorator模式
- Decorator模式
- decorator模式
- Decorator 模式
- decorator模式
- Decorator模式
- Decorator模式
- Decorator 模式
- Decorator模式
- Decorator模式
- Decorator模式
- Decorator模式
- 信用到底有多重要?它的影响太可怕!
- HIVE 设置任务名称
- swing 设置成全屏
- 微信浏览器视频video标签自动变成全屏的解决
- CMD命令
- Decorator模式
- 如何配置java环境以及常见的一些问题处理
- 考试篇(5.2) NSE4 题库 20. 诊断 ❀ 飞塔 (Fortinet) 网络安全专家
- Java并发编程:Thread类的使用
- 项目中sass管理
- 软件测试思想者
- C语言经典问题学习笔记之二
- go语言匿名函数的用法
- JeePlus项目 怎么实现图形化数据库 的步骤