分享

C++设计模式-Adapter

 幸福的乐土 2012-09-15

定义

  适配器将一个类的接口转换成客户希望的另外一个接口,该模式使得原来由于接口不兼容而不能一起工作的那些类可以一起工作。

结构

  类适配器包含两种结构:

  1.使用多重继承对一个接口与另一个接口进行匹配:如下图所示。


  2.依赖于对象组合,如下图所示。


理解

  在这么几种情况下可以使用类适配器模式:

  1.你想使用一个已经存在的类,而它的接口不符合你的需求。

  2.你想创建一个可以复用的类,该类可以与其他不相关的类(那些接口可能不一定兼容的类)或不可预见的类协同工作。

  3.你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。(仅使用于对象适配器)

应用

  1.ET++Draw通过使用一个TextShape适配器类的方式复用了ET++中的一些类,并将它们用于正文编辑。

  2.InterView2.6中也使用了诸如类适配器和对象适配器的概念。

代码

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. // Target  
  5. class stack  
  6. {  
  7. public:  
  8.     int pop(){}  
  9.     void posh(int ){}  
  10.     int get_size(){}  
  11.     bool is_empty(){}  
  12. private:  
  13.     //  
  14. };  
  15.   
  16. // Adaptee  
  17. class queue  
  18. {  
  19. public:  
  20.     int q_push(){}  
  21.     void q_pop(){}  
  22.     int front(){}  
  23.     int back(){}  
  24.     int get_size(){}  
  25.     bool is_empty(){}  
  26. private:  
  27.     //  
  28. };  
  29.   
  30. // Adapter  
  31. class q_stack : public stack, private queue  
  32. {  
  33. public:  
  34.     int pop()  
  35.     {  
  36.         // Actually, if we want queue acts as stack, we could use two queues to simulate a stack.  
  37.         queue::q_pop();  
  38.     }  
  39.     void push()  
  40.     {  
  41.         queue::q_push();  
  42.     }  
  43.     int get_size()  
  44.     {  
  45.         return queue::get_size();  
  46.     }  
  47.     bool is_empty()  
  48.     {  
  49.         return queue::is_empty();  
  50.     }  
  51. private:  
  52.     //  
  53. };  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多