浅谈设计模式之八——Decorator模式
来源:互联网 发布:linux touch 多个文件 编辑:程序博客网 时间:2024/05/21 06:03
先上uml图:
意图:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
uml解析:装饰者模式又名包装器,顾名思义就是给某个对象添加一些功能,而不是给整个类添加一些功能。Component跟Decorator是聚合关系,子类ConcreteDecoratorA和ConcreteDecoratorB实现具体对Component的修饰。
下面给出可执行的示例代码:
Decorator.h
#pragma once#include <iostream>using namespace std;class Component{public: Component(void); virtual ~Component(void); virtual void Operation()=0;};class ConcreteComponent:public Component{public: void Operation();};class Decorator:public Component{public: Decorator(Component *component):m_Component(component){} void Operation();protected: Component *m_Component;};class ConcreteDecoratorA:public Decorator{public: ConcreteDecoratorA(Component *component):Decorator(component){} void Operation(); void AddState();};class ConcreteDecoratorB:public Decorator{public: ConcreteDecoratorB(Component *component):Decorator(component){} void Operation(); void AddBehavior();};
Decorator.cpp
#include "Component.h"Component::Component(void){}Component::~Component(void){}void ConcreteComponent::Operation(){ cout<<"ConcreteComponent"<<endl;}void Decorator::Operation(){ m_Component->Operation();};void ConcreteDecoratorA::AddState(){ cout<<"AddState"<<endl;}void ConcreteDecoratorA::Operation(){ AddState(); m_Component->Operation();}void ConcreteDecoratorB::AddBehavior(){ cout<<"AddBehavior"<<endl;}void ConcreteDecoratorB::Operation(){ AddBehavior(); m_Component->Operation();}
main.cpp
#include "Component.h"int main(int argc,char **argv){ //未装饰 Component *p1=new ConcreteComponent; p1->Operation(); //DecoratorA Component *p2=new ConcreteDecoratorA(p1); p2->Operation(); //DecoratorB Component *p3=new ConcreteDecoratorB(p1); p3->Operation(); return 0;}
执行结果:
可看到分别对ConcreteComponent的装饰。
0 0
- 浅谈设计模式之八——Decorator模式
- 设计模式之八 --- 装饰模式(Decorator)
- 设计模式之八 --- 装饰模式(Decorator)
- 设计模式之八------Decorator(装饰)
- 设计模式(八)——Decorator 模式
- 浅谈JAVA设计模式之——装饰模式(Decorator)
- 设计模式之Decorator——家装篇
- 设计模式之Decorator——家装篇
- 设计模式之Decorator——家装篇
- 设计模式(c++)笔记之八(Decorator模式)
- 设计模式之Decorator
- 设计模式之 Decorator
- 设计模式之Decorator
- 设计模式之Decorator
- 设计模式之Decorator
- 设计模式之 decorator
- 设计模式之Decorator
- 设计模式之Decorator
- c# 使用Graphic 为图片添加水印 及文字
- jenkins 新建项目配置
- 定量装车鹤管应用辽阳石化 密闭装车系统保障汽油跑漏
- 淡淡的一天
- 练习10: 在windows MFC窗口中用CImage显示图片
- 浅谈设计模式之八——Decorator模式
- J2SE总结
- 语义分析的一些方法
- 一些思维训练
- 如何编辑PDF转换为PPT文件
- c语言exit和return区别
- jQuery异步提交form表单
- 欢迎使用CSDN-markdown编辑器
- C++析构函数为什么要为虚函数