设计模式学习之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();

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风行踩火轮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值