好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

adapter pattern

adapter pattern

adapter pattern,又称wrapper(包装) pattern

在软件系统中,由于应用环境的变化,常常需要将 “ 一些现存的对象 ” 放在新的环境中应用,但是新环境要求的接口是这些现存对象所不满足的。 Adapter 设计模式就是为了应对这种 “ 迁移的变化 ” ,以使客户系统既能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口。

“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.” ---GoF

 

将一个类的接口转化为客户端所期望的接口。适配器模式使得原本拥有不兼容接口的类能一起“工作”。--GoF

 

适配器一般有两种形式:

第一种形式

该形式是采用继承方式实现复用Adaptee接口。

 

实例解析:

    例如有一个人看电视,现在想换台了,有一个换台请求的接口,而电视机也可以接收信号换台,它拥有一个接收信号的接口,现在很清楚这两个类之间不兼容,我们需要一个适配器来使得这两个拥有不兼容接口的类一起工作。采取继承复用的方式。

  1   class   IdeaChange
   2   {
   3       public  :
   4          virutal  void  RequestChange( )= 0  ;
   5   };
   6   class   Tv
   7   {
   8       public  :
   9           void   AcceptRequest( );  
  10   };
  11   void   Tv::AcceptRequest( )
  12   {
  13      std::cout<< "  Accept the request of ChannelChange  " << std::endl; 
  14   }
  15   class  Adapter: public  IdeaChange, private   Tv
  16   {
  17       public  :
  18           void   RequestChange( );
  19   };
  20   void   Adapter::RequestChange( )
  21   {
  22      std::cout<< "  Request for change channel  " << std::endl;
  23       AcceptRequest( );
  24   }
  25  
 26   int  main( int  argc, char  **  argv)
  27   {
  28     Adapter a;
  29     a.RequestChange( );
  30     return   0  ;  
  31  }

运行结果

第二种形式

该形式是采用组合方式实现复用Adaptee接口。

还是上面一样的实例

  1   class   IdeaChange
   2   {
   3       public  :
   4          virutal  void  RequestChange( )= 0  ;
   5   };
   6   class   Tv
   7   {
   8       public  :
   9           void   AcceptRequest( );  
  10   };
  11   void   Tv::AcceptRequest( )
  12   {
  13      std::cout<< "  Accept the request of ChannelChange  " << std::endl; 
  14   }
  15   class  Adapter: public   IdeaChange
  16   {
  17       public  :
  18           Adapter( );
  19          ~ Adapter( );
  20           void   RequestChange( );
  21       private  :
  22          Tv*  t;
  23          
 24   };
  25   Adapter::Adapter( )
  26   {
  27      t= new   Tv( );
  28   }
  29  Adapter::~ Adapter( )
  30   {
  31       delete t;
  32   }
  33   void   Adapter::RequestChange( )
  34   {
  35      std::cout<< "  Request for change channel  " << std::endl;
  36      t-> AcceptRequest( );
  37   }
  38  
 39   int  main( int  argc, char  **  argv)
  40   {
  41     Adapter a;
  42     a.RequestChange( );
  43     return   0  ;  
  44  }

运行结果为



知识是一点一点积累起来的                  --小风

分类:  设计模式

标签:  设计模式

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于adapter pattern的详细内容...

  阅读:43次