Adapter mode Adapter (c++ design mode)


Convert the interface of a class to another interface that the customer wants. Adapter mode allows classes with incompatible interfaces to work together

Model advantages

  • Decouple the target class and the adaptor class
  • Increased class transparency and reusability
  • Flexibility and scalability are very good

Model disadvantages

  • A class adapter can only adapt to one adaptor at a time, and the adaptor cannot be the final class. The target abstract class can only be an interface, not a class
  • The method of replacing the adapter class with the object adapter in the adapter is troublesome

Applicable environment

The system needs to use the existing classes (adapter), and the interfaces of these classes do not meet the needs of the system, and even without the source code of these classes,
create a reusable class (target class/adapter) for and Some classes that are not very related to each other, including some classes that may be introduced in the future, work together

Adapter mode code

Class adapter


/*
 * @ 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;
}

Object adapter


/*
 * @ 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;
}

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/112885526