适配器模式Adapter(c++设计模式)


将一个类的接口转换成客户希望的另一个接口。 适配器模式让那些接口不兼容的类可以一起工作

模式优点

  • 将目标类和适配者类解耦
  • 增加了类的透明性和复用性
  • 灵活性和扩展性非常好

模式缺点

  • 类适配器一次只能适配一个适配者,且适配者不能为最终类,目标抽象类只能为接口,不能为类
  • 对象适配器在适配器中置换适配者类的方法比较麻烦

适用环境

系统需要使用现有的类(适配者),而这些类的接口不符合系统的需要,甚至没有这些类的源代码
创建一个可以复用的类(目标类/适配者),用于和一些彼此之间没有太大关联的类,包括一些可能在将来引进的类一起工作

适配器模式代码

类适配器


/*
 * @ Description: C++ Design Patterns___Adapter(Class scope)
 * @ version: v1.0
 * @ Author: WeissxJ
 */
#include<iostream>

class Target
{
public:
    virtual ~Target();
    virtual void request()=0;
    //...
};

class Adaptee
{
public:
    ~Adaptee(){}
    void specificRequest(){
        std::cout<<"specific request"<<std::endl;
    }
    // ...
};

class Adapter :public Target,private Adaptee
{
public:
    virtual void request(){
        specificRequest();
    }
    //...
};

int main(){
    Target *t=new Adapter();
    t->request();
    delete t;

    return 0;
}

对象适配器


/*
 * @ Description: C++ Design Patterns___Adapter(Object scope)
 * @ version: v1.0
 * @ Author: WeissxJ
 */
#include<iostream>

class Target
{
public:
    virtual ~Target();
    virtual void request()=0;
    //...
};

class Adaptee
{
public:
    ~Adaptee(){}
    void specificRequest(){
        std::cout<<"specific request"<<std::endl;
    }
    // ...
};

class Adapter :public Target
{
public:
    Adapter():adaptee(){}

    ~Adapter(){
        delete adaptee;
    }
    
    void request(){
        adaptee->specificRequest();
        //...
    }
    //...
private:
    Adaptee *adaptee;
    // ...
};

int main(){
    Target *t=new Adapter();
    t->request();
    delete t;

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值