Decorator (C++实现)

// Decorator.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;

 

class Component
{
public:
 Component()
 {
 }
 virtual ~Component()
 {
 }

 virtual void Operation()=0;
};

 

 

 

class ConcreteComponent :public Component
{
public:
 ConcreteComponent()
 {
  cout<<"Construction of ConcreteComponet"<<endl;
 }
 virtual ~ConcreteComponent()
 {
 }

 virtual void Operation()
 {
      cout<<"Opearation of ConcreteComponet"<<endl; 
 }
};

 

 

 

class Decorator:public Component
{
public:
 Decorator(Component *m_p):m_pComponet(m_p)
 {
  
 }

 virtual ~Decorator()
 {
  delete m_pComponet;
  m_pComponet=NULL;
 }

 virtual void Operation()
 {
  m_pComponet->Operation();
 }

private:
 Component *m_pComponet;

};

class ConcreteDecorateA:public Decorator
{
 public:
 ConcreteDecorateA(Component* m_p):Decorator(m_p)
 {
  cout<<"Construction of  ConcreteDecorateA"<<endl;
 }
 virtual ~ConcreteDecorateA()
 {
 }
 virtual void Operation()
 {
  cout<<"Operation of ConcreteDecorateA"<<endl;
  Decorator::Operation();
  drawLine();
 }


private:
 void drawLine()
 {
  cout<<"----------------------------"<<endl;
 }

};


class ConcreteDecorateB:public Decorator
{
 public:
 ConcreteDecorateB(Component* m_p):Decorator(m_p)
 {
  cout<<"Construction of  ConcreteDecorateB"<<endl;
 }
 virtual ~ConcreteDecorateB()
 {
 }
 virtual void Operation()
 {
  cout<<"Operation of ConcreteDecorateB"<<endl;
  Decorator::Operation();
  drawNumber();
 }
 
private:
 void drawNumber()
 {
  cout<<"1-2-3-4-5-6-7-8-9-0"<<endl;
 }

};
int _tmain(int argc, _TCHAR* argv[])
{
 Component* pComponent = new ConcreteComponent();
 Decorator *pDecorator1 = new ConcreteDecorateA(pComponent);
 Decorator *pDecorator2 = new ConcreteDecorateB(pDecorator1);
 pDecorator2->Operation();

 return 0;
}

 

 

结果:

 

 

posted on 2011-05-25 18:18  IT@民工  阅读(182)  评论(0编辑  收藏  举报

导航