结构型模式三之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、  这种比继承更灵活机动的特性,也同时意味着装饰模式比继承更加易于出错。

 

缺点:

       由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使得设计比较易于进行。但是,在另一个方面,使用装饰模式会产生比使用继承关系更富哦的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。

原创粉丝点击