温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++装饰模式怎么使用

发布时间:2021-11-30 17:53:16 来源:亿速云 阅读:129 作者:iii 栏目:开发技术

这篇文章主要介绍“C++装饰模式怎么使用”,在日常操作中,相信很多人在C++装饰模式怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++装饰模式怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

C++ 设计模式 装饰模式
在结构型模式中装饰模式给我留下了深刻的印象,其中也感觉到在设计模式中基本都是
依赖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. }

到此,关于“C++装饰模式怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI