《装饰模式》

来源:互联网 发布:刷机精灵for mac 编辑:程序博客网 时间:2024/05/01 22:04

自我理解就是把对象重新装饰了一遍。通过继承同一个基类。而不用添加额外的类了。。。。

上图吧

通过修饰类达到我们想要的效果。修饰类通常初始化了基类。

[cpp] view plaincopy
  1. // Decorator.cpp : 定义控制台应用程序的入口点。  
  2. //************************************************************************/      
  3. /* @filename    Decorator.cpp 
  4. @author       wallwind   
  5. @createtime    2012/10/29 22:42 
  6. @function     命令模式 
  7. @email       wochenglin@qq.com   
  8. */      
  9. /************************************************************************/     
  10.   
  11. #include "stdafx.h"  
  12. #include <iostream>  
  13.   
  14. using namespace std;  
  15.   
  16. class Widget  
  17. {  
  18. public:  
  19.     Widget(){}  
  20.     virtual ~Widget(){}  
  21.   
  22.     virtual void show()=0;  
  23. };  
  24.   
  25. class TextField:public Widget  
  26. {  
  27. public:  
  28.     TextField(int ix,int iy)  
  29.         :x(ix),y(iy)  
  30.     {  
  31.   
  32.     }  
  33.     ~TextField(){}  
  34.   
  35.     void show()  
  36.     {  
  37.         cout<<"x:"<<x<<endl;  
  38.         cout<<"y:"<<y<<endl;  
  39.   
  40.     }  
  41. private:  
  42.     int x;  
  43.     int y;  
  44. };  
  45. class Decorator:public Widget  
  46. {  
  47. public:  
  48.     Decorator(Widget* widget)  
  49.         :m_widget(widget)  
  50.     {}  
  51.     virtual ~Decorator()  
  52.     {  
  53.         delete m_widget;  
  54.     }  
  55.   
  56.     void show()  
  57.     {  
  58.         m_widget->show();  
  59.         cout<<"Decorator:show()"<<endl;  
  60.     }  
  61. private:  
  62.     Widget* m_widget;  
  63. };  
  64.   
  65. class BorderDecorator :public Decorator  
  66. {  
  67. public:  
  68.     BorderDecorator(Widget* widget)  
  69.         :Decorator(widget)  
  70.     {  
  71.   
  72.     }  
  73.     void show()  
  74.     {  
  75.         Decorator::show();  
  76.         cout<<"BorderDecorator:show()"<<endl;  
  77.     }  
  78. };  
  79.   
  80. class ScrollDecorator :public Decorator  
  81. {  
  82. public:  
  83.     ScrollDecorator(Widget* widget)  
  84.         :Decorator(widget)  
  85.     {  
  86.   
  87.     }  
  88.   
  89.     void show()  
  90.     {  
  91.         Decorator::show();  
  92.         cout<<"ScrollDecorator:show()"<<endl;  
  93.     }  
  94. };  
  95.   
  96.   
  97. int _tmain(int argc, _TCHAR* argv[])  
  98. {  
  99.   
  100. Widget* aWidget = new BorderDecorator(  
  101.   new BorderDecorator(  
  102.   new ScrollDecorator(  
  103.   new TextField( 80, 24 ))));</p><p> aWidget->show();
  104.   return 0;  
  105. }  

原创粉丝点击