设计模式学习之Decorator模式

在OO设计和开发过程中,可能会遇到以下情况:需要为一个已经定义好的类添加新的职责,通常情况下定义一个新的类继承定义好的类,这样会带来一个问题:通过继承的方式解决这样的问题带来了系统的复杂性和继承深度变得很深;而Decarator提供了一种给类增加职责的方法,不是通过继承实现,而是通过组合实现;结构图如下:

在结构图中,ConcreteComponent和Decorator需要同样的接口,因此ConcreteComponent和Decorator有相同的父类,这里会有人问,让Decorator直接维护一个指向ConcreteComponent引用(指针)不就可以达到相同的效果了,答案是肯定的但也是否定的。肯定的是可以通过这个方式实现,否定的是不要采用这种方式实现,因为通过这种方式你就只能为这个特定的ConcreteComponent提供修饰操作了,当有了一个新的ConcreteComponent时又需要新建一个Decorator类来实现;但是通过类图ConcreteComponent和Decorator有一个公共的基类,就可以利用OO中多态的思想来实现只要是Component型别的对象都可以提供修饰操作的类这种情况下就算新建100个Component型别的类ConcreteComponent,也都可以由Decorator一个类来搞定,这就是Decorator模式的关键所在了。

其实现代码如下:

#ifndef _DECORATOR_H
#define _DECORATOR_H

class Component
{
public:
 Component();
 virtual ~Component();

 virtual void Operation();
};

class ConcreteComponent : public Component
{
public:
 ConcreteComponent();
 virtual ~ConcreteComponent();

 void Operation();
};

class Decorator : public Component
{
public:
 Decorator(Component* pCom);
 virtual ~Decorator();

 void Operation();

扫描二维码关注公众号,回复: 3274029 查看本文章

protected:
 Component* pMCom;
};

class ConcreteDecorator : public Decorator
{
public:
 ConcreteDecorator(Component* pCom);
 virtual ~ConcreteDecorator();

 void Operation();
 void AddedBehavior();
};

#endif

#include "Decorator.h"
#include <iostream>

Component::Component()
{

}

Component::~Component()
{

}

void Component::Operation()
{

}

ConcreteComponent::ConcreteComponent()
{
}

ConcreteComponent::~ConcreteComponent()
{
}

void ConcreteComponent::Operation()
{
 cout<<"ConcreteComponent operation..."<<endl;
}

Decorator::Decorator(Component* pCom)
{
 this->pMCom = pCom;
}

Decorator::~Decorator()
{

}

void Decorator::Operation()
{
 cout<<"Decorator operation..."<<endl;
}

ConcreteDecorator::ConcreteDecorator(Component* pCom) : Decorator(pCom)
{
}

ConcreteDecorator::~ConcreteDecorator()
{

}

void ConcreteDecorator::AddedBehavior()
{
 cout<<"ConcreteDecorator opration..."<<endl;
}

void ConcreteDecorator::Operation()
{
 pMCom->Operation();
 this->AddedBehavior();
}

#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;

}

猜你喜欢

转载自blog.csdn.net/cheng7068/article/details/8519791