适配器模式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;
}

猜你喜欢

转载自blog.csdn.net/qq_43477024/article/details/112885526