Florian 发表于 2013-1-4 02:22:57

适配器模式(Adapter)

<div id="cnblogs_post_body"> 适配器模式(Adapter)

适配器模式(Adapter)
意图:将类的一个接口转换成用户希望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以一起工作。
应用:将图形类接口适配到用户界面组件类中。
模式结构:
http://images.cnblogs.com/cnblogs_com/fanzhidongyzby/设计模式/适配器.jpg
心得:
适配器模式一般应用在具有相似接口可复用的条件下。目标接口(Target)是需要适配器的实现的接口(输出),被适配的接口(Adaptee)拥有与目标接口不兼容的接口,适配器需要根据功能逻辑将Adaptee的接口“映射”Target接口上。使用多继承实现的方式成为类适配器,它通过公有继承Target接口,私有继承Adaptee接口实现。而针对对象的适配器稍显灵活,因此这里重点介绍对象适配器。适配器(Adapter)组合了Adaptee接口,使用函数调用的方式产生兼容的Target接口实现。
举例:
按照图中的设计类图,我们用C++实现一个简单的适配器:
<div class="cnblogs_code">//目标接口
class Target
{
public:
    virtual void request()=0;
    virtual ~Target(){}
};
//被适配的接口
class Adaptee
{
public:
    virtual void specificRequest()
    {
      cout<<"特殊的接口"<<endl;
    }
};
//适配器
class Adapter:public Target
{
    Adaptee *adaptee;
public:
    Adapter(Adaptee*ad):adaptee(ad){}
    virtual void request()
    {
      adaptee->specificRequest();//适配请求
    }
    virtual ~Adapter()
    {
      delete adaptee;
    }
};
页: [1]
查看完整版本: 适配器模式(Adapter)