其他分享
首页 > 其他分享> > 装饰模式

装饰模式

作者:互联网

原文链接:http://www.cnblogs.com/cxrs/archive/2011/12/01/2270957.html

 装饰模式,

   动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

// Decorator.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class IComponent
{
public:
 virtual void process() = 0;

};

class Component : public IComponent
{
public:
 virtual void process()
 {
  cout<<"Component process"<<endl;
 }
};

class Decorator: public IComponent
{
public:
 virtual void process()
 {
  if ( !myComponent)
   myComponent->process();
 }
 virtual void setComponent( IComponent *component )
 {
  myComponent = component;
 }
 ~Decorator()
 {
  if (myComponent)
   delete myComponent;
 }
protected:
 IComponent *myComponent;
};

class ConcreateDecoratorA: public Decorator
{
public:
 virtual void process()
 {
  myComponent->process();
  cout<<"ConcreateDecoratorA process"<<endl;
 }
};

class ConcreateDecoratorB: public Decorator
{
public:
 virtual void process()
 {
  myComponent->process();
  cout<<"ConcreateDecoratorB process"<<endl;
 }
};

int _tmain(int argc, _TCHAR* argv[])
{
 Component *pComponent = new Component();

 ConcreateDecoratorA *pDecoratorA = new ConcreateDecoratorA();
 ConcreateDecoratorB *pDecoratorB = new ConcreateDecoratorB();

 pDecoratorA->setComponent( pComponent );
 pDecoratorA->process();

 pDecoratorB->setComponent( pDecoratorA );
 pDecoratorB->process();

 system("pause");
 return 0;
}

 

转载于:https://www.cnblogs.com/cxrs/archive/2011/12/01/2270957.html

标签:process,void,virtual,public,class,模式,myComponent,装饰
来源: https://blog.csdn.net/weixin_30642267/article/details/97564524