C++ 设计模式 装饰模式(Decorator Pattern)

C++ 设计模式 装饰模式

在结构型模式中装饰模式给我留下了深刻的印象,其中也感觉到在设计模式中基本都是
依赖C++的多态来实现,装饰模式也不例外,他允许在不改变原有类的代码的基础上,
不通过直接继承原有类的代码通过一个抽象接口层进行实现,甚至可以随意的组合,
所以这里记录之以备使用
下面是模型图:


下面是一个简单的模拟代码,模拟本来一个工具只有写功能,但是我们要不断的扩充其
功能让它有听有读的功能:
这是跑出来的结果
----source tool----
i can write!!
-----can listen tool-----
i can write!!
i can listene !!
----can read tool------
i can write!!
i can read !!
----can listen and  read tool------
i can write!!
i can read !!
i can listene !!


下面是代码:

点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;
  3. /*装饰模式
  4.  *装饰者模式(Decorator Pattern)动态的给一个对象添加一些额外的职责
  5.  */
  6. class ABS_TOOL
  7. {
  8. public:
  9.    virtual ~ABS_TOOL(){}
  10.    virtual void fun() = 0; //功能接口
  11. };


  12. class write:public ABS_TOOL
  13. {
  14. public:
  15.     virtual void fun()
  16.     {
  17.         cout<<"i can write!!\n";
  18.     }
  19. };

  20. class listen:public ABS_TOOL //继承
  21. {
  22. public:
  23.     virtual ~listen(){}
  24.     listen(ABS_TOOL* tool) //依赖
  25.     {
  26.         this->tool = tool;
  27.     }
  28.      virtual void fun()
  29.     {
  30.         tool->fun();
  31.         cout<<"i can listene !!\n";
  32.     }
  33. private:
  34.     ABS_TOOL* tool; //聚合
  35. };

  36. class read:public ABS_TOOL //继承
  37. {
  38. public:
  39.     virtual ~read(){}
  40.     read(ABS_TOOL* tool) //依赖
  41.     {
  42.         this->tool = tool;
  43.     }
  44.      virtual void fun()
  45.     {
  46.         tool->fun();
  47.         cout<<"i can read !!\n";
  48.     }
  49. private:
  50.     ABS_TOOL* tool; //聚合
  51. };


  52. int main(void)
  53. {
  54.     cout<<"----source tool----\n";
  55.     write test1;
  56.     test1.fun();
  57.     cout<<"-----can listen tool-----\n";
  58.     listen test2(&test1);
  59.     test2.fun();
  60.      cout<<"----can read tool------\n";
  61.     read test3(&test1);

  62.     test3.fun();
  63.      cout<<"----can listen and read tool------\n";
  64.     listen test4(&test3);
  65.     test4.fun();


  66.     return 0;
  67. }

作者微信:

               

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7728585/viewspace-2137337/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/7728585/viewspace-2137337/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值