设计模式-装饰模式
来源:互联网 发布:期货软件app 编辑:程序博客网 时间:2024/05/29 07:35
适用情境:给一个类添加一些额外的功能,而不修改原来类的代码.添加的功能一般不是非常重要的核心功能,而是较少使用的次要功能.添加的功能放在一个单独的类中,客户端可以对添加的功能进行选择.
优点:新添加的功能不影响被装饰类的功能,不增加被装饰类的复杂度.
缺点:需要修改客户端代码.
// component.h#ifndef COMPONENT_H#define COMPONENT_Hclass Component{public: Component(); virtual void Operation() = 0;};#endif // COMPONENT_H
// component.cpp#include "component.h"Component::Component(){}
// concretecomponent.h#ifndef CONCRETECOMPONENT_H#define CONCRETECOMPONENT_H#include "component.h"class ConcreteComponent : public Component{public: ConcreteComponent(); virtual void Operation();};#endif // CONCRETECOMPONENT_H
// concretecomponent.cpp#include <iostream>#include "concretecomponent.h"ConcreteComponent::ConcreteComponent(){}void ConcreteComponent::Operation(){ std::cout << "ConcreteCompoent::operation()" << std::endl;}
// decorator.h#ifndef DECORATOR_H#define DECORATOR_H#include "component.h"class Decorator : public Component{public: Decorator(Component *tmp); virtual void Operation();public: Component *m_component;};#endif // DECORATOR_H
// decorator.cpp#include "decorator.h"Decorator::Decorator(Component *tmp){ m_component = tmp;}void Decorator::Operation(){ m_component->Operation();}
// concretedecorator.h#ifndef CONCRETEDECORATOR_H#define CONCRETEDECORATOR_H#include "decorator.h"class ConcreteDecorator : public Decorator{public: ConcreteDecorator(Component *tmp); virtual void Operation(); virtual void NewOperation();};#endif // CONCRETEDECORATOR_H
// concretedecorator.cpp#include <iostream>#include "concretedecorator.h"ConcreteDecorator::ConcreteDecorator(Component *tmp) : Decorator(tmp){}void ConcreteDecorator::Operation(){ m_component->Operation(); NewOperation();}void ConcreteDecorator::NewOperation(){ std::cout << "ConcreteDecorator::NewOperation()" << std::endl;}
客户端:
// main.cpp#include <iostream>#include "component.h"#include "decorator.h"#include "concretedecorator.h"#include "concretecomponent.h"using namespace std;int main(int argc, char *argv[]){ Component *component = new ConcreteComponent(); Component *component1 = new ConcreteDecorator(component); component1->Operation(); return 0;}
0 0
- 设计模式---装饰模式
- 设计模式:装饰模式
- 设计模式------装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式 装饰模式
- 设计模式----装饰模式
- 设计模式-【装饰模式】
- 设计模式--装饰模式
- 设计模式装饰模式
- 设计模式 - 装饰模式
- 设计模式-----装饰模式.
- 设计模式-----装饰模式.
- [ 设计模式 ] 装饰模式!
- 设计模式:装饰模式
- 设计模式 - 装饰模式
- 设计模式 - 装饰模式
- PaddlePaddle
- MediaRecorder视频的录制和播放
- HDU 5113 Black And White (dfs、剪枝)
- WebService CXF学习(入门篇2):HelloWorld
- 在linux上,用scalac编译在Spark平台上运行的scala程序
- 设计模式-装饰模式
- 总结
- Java线程和多线程(十一)——BlockingQueue
- leetcode解题报告:338. Counting Bits
- Scala学习笔记1——初始Scala
- C/C++中函数参数传递详解
- Android开发中的第三方支付SDK的接入与使用(支付宝+微信支付+银联)
- 第六课 Fragments-界面片段
- Fragment与Activity间的通信(方法概述)