zoukankan      html  css  js  c++  java
  • 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 }
    复制代码

    运行结果为

    分类: 设计模式
    标签: 设计模式
  • 相关阅读:
    我家笨笨爱上了小笨
    Outlook备份全攻略
    中国男篮有希望!评中国vs西班牙之战
    男为己悦者穷
    转:15则笑话
    看看你家乡在全国的位置2008最新各省市的GDP和人均收入排名
    锦江之星 .VS. 如家HOME INN
    学会心理养生
    另眼看北京奥运
    南方餐馆与北方餐馆
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2821940.html
Copyright © 2011-2022 走看看