设计模式-结构型-装饰
原创
©著作权归作者所有:来自51CTO博客作者shixin_0125的原创作品,请联系作者获取转载授权,否则将追究法律责任
#pragma once
#ifndef DECORATOR_H
#define DECORATOR_H
class Component
{
public:
Component(){}
virtual ~Component(){}
virtual void Operation() = 0;
};
class Decorator : public Component
{
public:
Decorator(Component* pComponent)
: m_pComponent(pComponent){}
virtual ~Decorator();
protected:
Component* m_pComponent;
};
class ConcreateComponent : public Component
{
public:
ConcreateComponent(){}
virtual ~ConcreateComponent(){}
virtual void Operation();
};
class ConcreateDecorator : public Decorator
{
public:
ConcreateDecorator(Component* pComponent)
: Decorator(pComponent){}
virtual ~ConcreateDecorator(){}
virtual void Operation();
private:
void AddedBehavior();
};
#endif
#include "StdAfx.h"
#include "decorator_impl.h"
#include <iostream>
Decorator::~Decorator()
{
delete m_pComponent;
m_pComponent = NULL;
}
void ConcreateComponent::Operation()
{
std::cout << "Operation of ConcreateComponent\n";
}
void ConcreateDecorator::Operation()
{
m_pComponent->Operation();
AddedBehavior();
}
void ConcreateDecorator::AddedBehavior()
{
std::cout << "AddedBehavior of ConcreateDecorator\n";
}
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include "decorator_impl.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Component* pComponent = new ConcreateComponent();
cout<<"before decorator"<<endl;
pComponent->Operation();
cout<<endl;
Decorator* pDecorator = new ConcreateDecorator(pComponent);
cout<<"after decorator"<<endl;
pDecorator->Operation();
delete pDecorator;
system("pause");
return 0;
}