标签:设计模式 decorator 装饰模式 design-pattern
在开发过程中,有时会遇到需要向已经定义好的类添加新功能的需求,这时候通常的做法就是定义一个新类,继承这个类,在新类中添加新功能。
采用继承的方式来实现,在使用时,我们经常使用父类的指针或引用通过多态技术来调用子类的接口,但这样就会遇到一个问题:再向子类添加方法时,也需要向父类添加方法,否则通过父类指针或引用就调用不到这个方法。所以Decorator模式没有采用继承来实现,而是采用组合的方式来实现。类结构图如下图所示:
类ConcreteComponent和类Decorator有相同的接口,所以都继承自Component。在Decorator中,有一个指向Component的指针(引用),通过这个指针来调用ConcreteComponent中的函数Operation。
下面是实现:
//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.cpp
//Decorator.cpp
#include"Decorator.h"
#include<iostream>
Component::~Component(){}
void Component::Operation(){}
Component::Component(){}
ConcreteComponent::ConcreteComponent(){}
ConcreteComponent::~ConcreteComponent(){}
void ConcreteComponent::Operation()
{
std::cout << "ConcreteComponent operation" << std::endl;
}
Decorator::Decorator(Component* com)
{
_com = com;
}
Decorator::~Decorator()
{
delete _com;
}
void Decorator::Operation(){}
ConcreteDecorator::ConcreteDecorator(Component* com) :Decorator(com)
{}
ConcreteDecorator::~ConcreteDecorator(){}
void ConcreteDecorator::AddedBehavior()
{
std::cout << "ConcreteDecorator::AddedBehavior..." << std::endl;
}
void ConcreteDecorator::Operation()
{
_com->Operation();
AddedBehavior();
}
//main.cpp
//main.cpp
#include"Decorator.h"
int main()
{
Component* com = new ConcreteComponent();
Decorator* dec = new ConcreteDecorator(com);
dec->Operation();
delete dec;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:设计模式 decorator 装饰模式 design-pattern
原文地址:http://blog.csdn.net/kangroger/article/details/46866949