Home  >  Article  >  Backend Development  >  A brief introduction to the adapter pattern in C++ design patterns

A brief introduction to the adapter pattern in C++ design patterns

黄舟
黄舟Original
2017-01-17 13:32:031190browse

Adapter mode (Adapter): Convert the interface of a class into another interface that the customer wants. The Adapter pattern enables classes that would otherwise not work together due to incompatible interfaces to work together.

When to use the Adapter pattern:

It is needed when two classes do the same or similar things, but have different interfaces.

Use the adapter mode when it is not easy for both parties to modify.

Pattern implementation:

[code]//Target
class Target{
public:
    virtual void Request(){
        std::cout << "Target::Request\n";
    }
};

//Adaptee适配(者)的类
class Adaptee{
public:
    void SpecificRequest(){
        std::cout << "Adaptee::SpecificRequest\n";
    }
};

//Adapter,适配器
class Adapter: public Target, Adaptee{
public:
    void Request(){
        Adaptee::SpecificRequest();
    }
};

Client:

[code]//Client
int main(){
    Target *targetObj = new Adapter();
    targetObj->Request();  //Output: Adaptee::SpecificRequest
    delete targetObj;
    targetObj = NULL;

    return 0;
}

The above is the content of the C++ design pattern brief introduction to the adapter pattern. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn