当前位置:   article > 正文

c++之桥接模式_桥接模式九阴真经

桥接模式九阴真经

桥接模式

定义:把抽象部分和它的实现部分分离,使得它们都可以独立的变化

栗子场景:华山派和崆峒派先后获得了武林秘籍辟邪剑谱和九阴真经,于是开始苦练此功..

UML类图

代码:

  1. #include<iostream>
  2. using namespace std;
  3. class Sects;
  4. //功夫
  5. class Kungfu
  6. {
  7. public:
  8. virtual void practice() = 0;
  9. };
  10. //九阴真经
  11. class JiuyinZj :public Kungfu
  12. {
  13. public:
  14. virtual void practice()
  15. {
  16. cout << "@九阴真经。注:玄门内功,至阴至柔" << endl;
  17. }
  18. };
  19. //辟邪剑谱
  20. class PixieJp :public Kungfu
  21. {
  22. public:
  23. virtual void practice()
  24. {
  25. cout << "@辟邪剑谱,注:欲练此功,必先自宫" << endl;
  26. }
  27. };
  28. //门派
  29. class Sects{
  30. public:
  31. Sects() :m_kungfu(nullptr){}
  32. void setMartialarts(Kungfu* m)
  33. {
  34. this->m_kungfu = m;
  35. }
  36. Kungfu* getKungfu()
  37. {
  38. return m_kungfu;
  39. }
  40. virtual void practice() = 0;
  41. private:
  42. Kungfu *m_kungfu; //桥接
  43. };
  44. //华山
  45. class HuaShan :public Sects
  46. {
  47. public:
  48. void practice()
  49. {
  50. getKungfu()->practice();
  51. }
  52. };
  53. //崆峒
  54. class KongTong :public Sects
  55. {
  56. public:
  57. void practice()
  58. {
  59. getKungfu()->practice();
  60. }
  61. };
  62. //客户端
  63. int main()
  64. {
  65. Sects *sects = new HuaShan;
  66. cout << "华山派弟子正在练习:" << endl;
  67. sects->setMartialarts(new JiuyinZj);
  68. sects->practice();
  69. sects->setMartialarts(new PixieJp);
  70. sects->practice();
  71. sects = new KongTong;
  72. cout << "崆峒派弟子正在练习:" << endl;
  73. sects->setMartialarts(new JiuyinZj);
  74. sects->practice();
  75. sects->setMartialarts(new PixieJp);
  76. sects->practice();
  77. if (sects)
  78. {
  79. delete sects;
  80. sects = nullptr;
  81. }
  82. return 0;
  83. }

效果:

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号