结构型模式三之Decorator
来源:互联网 发布:淘宝手机流量购买 编辑:程序博客网 时间:2024/05/07 22:11
1. 意图
动态给一个对象添加一些额外的职责,
2. UML
3. code
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_H_Decorator.cpp
//Decorator.cpp#include "Decorator.h"#include <iostream>Component::Component(){}Component::~Component(){ }void Component::Operation(){ }ConcreteComponent::ConcreteComponent(){ }ConcreteComponent::~ConcreteComponent(){ }void ConcreteComponent::Operation(){std::cout<<"ConcreteComponent operation..."<<std::endl;}Decorator::Decorator(Component* com){this->_com = com;}Decorator::~Decorator(){delete _com;}void Decorator::Operation(){ }ConcreteDecorator::ConcreteDecorator(Component* com):Decorator(com){ }ConcreteDecorator::~ConcreteDecorator(){ }void ConcreteDecorator::AddedBehavior(){std::cout<<"ConcreteDecorator::AddedBehacior...."<<std::endl;}void ConcreteDecorator::Operation(){_com->Operation();this->AddedBehavior();}
main.cpp
//main.cpp#include "Decorator.h"#include <iostream>using namespace std;int main(int argc,char* argv[]){Component* com = new ConcreteComponent();Decorator* dec = new ConcreteDecorator(com);dec->Operation();delete dec;return 0;}
4. output
5. 使用情况
1、 需要扩展一个类的功能,或者给一个类增加附加责任。
2、 需要动态地给一个对象增加功能,这些功能可以动态地撤销。
3、 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。
6.优缺点
优点:
1、 装饰模式与继承关系的目的都是要扩展对象的功能但是装饰模式可以提供比继承更多的灵活性。
2、 通过使用不同的具体装饰类以及这些装饰类的排列组合设计师可以创造出很多不同行为的组合。
3、 这种比继承更灵活机动的特性,也同时意味着装饰模式比继承更加易于出错。
缺点:
由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使得设计比较易于进行。但是,在另一个方面,使用装饰模式会产生比使用继承关系更富哦的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。
- 结构型模式三之Decorator
- 结构型模式之Decorator模式
- 结构型模式之四---Decorator
- 结构型模式之装饰DECORATOR
- 结构型模式之装饰(Decorator)
- 结构模式之Decorator(油漆工)
- 结构模式之Decorator(油漆工)
- 【设计模式攻略】结构型模式之Decorator模式
- 设计模式笔记-结构型模式之四--Decorator
- 结构型模式之装饰模式(Decorator Pattern)C++实现
- 结构型模式之装饰者模式(Decorator)
- 结构型模式之装饰模式(Decorator)
- 结构型模式之装饰模式(Decorator)
- 设计模式(结构型)之装饰者模式(Decorator Pattern)
- 【设计模式】结构型模式之装饰器Decorator
- 7种结构型模式之:装饰器模式(Decorator)
- 九、结构模式之装饰(Decorator)模式
- 译-设计模式-结构模式之Decorator
- Oracle&C# 导出多Sheet Excel ,使用Oracle Package (不积跬步,无以至千里)
- 统计文件的数量
- 设计模式之代理模式 (Proxy Pattern)
- ubuntu 下如何得到 linux 内核的源代码
- NSInvocation的使用
- 结构型模式三之Decorator
- IOS 根据日期,获取该日期所在周,月,年的开始日期,结束日期 的方法
- inode 介绍
- chgrp 的使用
- 如何修改linux上的机器名
- c++ 显性转换explicit
- chown的使用方法
- 配置WP开发环境问题:Visual Studio setup cannot run in compatibility mode
- 用指针逆序输出字符串