关于C++ decorator模式的运行结果?
源程序如下:
//decorator.h
#ifndef _DECORATOR_H_
#define _DECORATOR_H_
#include <iostream>
using namespace std;
class Component
{
public:
virtual ~Component(){}
virtual void Operation()=0{}
protected:
Component(){}
};
class ConcreteComponent : public Component
{
public:
ConcreteComponent(){}
virtual ~ConcreteComponent(){}
virtual void Operation()
{cout<<"ConcreteComponent::ConcreteComponent..."<<endl;}
};
classDecorator : public Component
{
public:
Decorator(Component *com):_com(com){}
virtual ~Decorator()
{
delete _com;
_com = NULL;
}
virtual void Operation()
{
cout<<"Decorator::Decorator..."<<endl;
}
protected:
Component *_com;
};
class ConcreteDecorator : public Decorator
{
public:
ConcreteDecorator(Component *com) : Decorator(com){}
virtual ~ConcreteDecorator(){}
void operation()
{
_com->Operation();
this->addedBehavior();
}
private:
void addedBehavior()
{cout<<"ConcreteDecorator::addedBehavior..."<<endl;}
};
#endif
//mainframe.cpp
#include "decorator.h"
#include <stdlib.h>
void main()
{
Component *com = new ConcreteComponent();
Decorator *dec = new ConcreteDecorator(com);
//com->Operation();
dec->Operation();
delete dec;
system("pause");
}
按照对书中关于decorator模式的理解,调用dec->Operation()后运行的结果应该包含ConcreteComponent类中的operation内容和ConcreteDecorator类中的addedBehavior()内容,但不知为什么运行结果是Decorator类operation中的内容,请各大牛指教
[解决办法]
void operation()
这个operation应该是Operation,注意大小写