适配器模式 C++实现

[+]


转自:http://blog.csdn.net/huazhongkejidaxuezpp/article/details/20389747



适配器模式

继承实现

Adaptee类没有Request方法,而客户期待这个方法。为了使客户能够使用Adaptee类,提供一个中间环节,即类Adapter类,Adapter类实现了Target接口,并继承自AdapteeAdapter类的Request方法重新封装了AdapteeSpecificRequest方法,实现了适配的目的。

角色包括:

目标(Target)角色:这是客户所期待的接口。

源(Adaptee)角色:需要适配的类

适配器(Adapter)角色:把源接口转换成目标接口。这一角色必须是类

   继承实现的UML图:

      

 

#include<iostream> 

using   namespace   std; 

       

// "ITarget" 

class  Target 

public: 

    // Methods 

    virtual void   Request(){}

}; 

       

// "Adaptee" 

class   Adaptee 

public: 

    // Methods 

    void SpecificRequest() 

    { 

        cout<<"CalledSpecificRequest()"<<endl; 

    } 

}; 

       

// "Adapter" 

class Adapter : public Adaptee, public Target 

public: 

    // Implements ITargetinterface 

    void Request() 

    { 

        //Possibly do some data manipulation 

        // andthen call SpecificRequest   

        this->SpecificRequest(); 

    } 

}; 

       

       

int main() 

    // Create adapter and place arequest 

    Target *t = newAdapter(); 

    t->Request(); 

       

    return0; 

}

组合实现

    组合实现的UML图:
     

#include<iostream> 

using namespace std; 

       

// "ITarget" 

class Target 

public: 

    // Methods 

    virtual void Request(){}

}; 

       

// "Adaptee" 

class Adaptee 

public: 

    // Methods 

    void SpecificRequest() 

    { 

        cout<<"CalledSpecificRequest()"<<endl; 

    } 

}; 

       

// "Adapter" 

class Adapter : public   Target 

private: 

    Adaptee *adaptee; 

       

public: 

    Adapter() 

    { 

        adaptee =new   Adaptee(); 

    } 

~ Adapter() //为防止内存泄露,本人在原代码的基础上添加的

    { 

         if(NULL!= adaptee)

         delete adaptee;

         adaptee=NULL;

    } 


       

    // Implements ITargetinterface 

    void Request() 

    { 

        //Possibly do some data manipulation 

        // andthen call SpecificRequest   

        adaptee->SpecificRequest(); 

    } 

}; 

       

       

int main() 

    // Create adapter and place arequest 

    Target *t = new Adapter(); 

    t->Request(); 

       

    return0; 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值