装饰模式

原文链接: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

上一篇:【react框架】学习记录3-什么是react的组件、函数式与类式、受控与非受控、简单与复杂


下一篇:Vue – 基础学习(3):动态加载和注册组件