<aside> 💡

适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

</aside>

结构图

image.png

应用场景

题目

https://kamacoder.com/problempage.php?pid=1085

#include <iostream>

// Target类
class TypeC{
public:
    virtual void chargeWithTypeC(){
        std::cout << "TypeC" << std::endl;
    }

    virtual ~TypeC() = default;
};

// Adaptee类
class USB{
public:
    void chargeWithUSB(){
        std::cout << "USB Adapter" << std::endl;
    }
};

// Adapter类,继承于Target类
class Adapter: public TypeC{
private:
    // 包含一个Adaptee类的实例
    USB* usb;
public:
    Adapter(): usb(new USB()){}

    ~Adapter(){
        delete usb;
    }

    // 包装源接口,将其转换为目标接口
    void chargeWithTypeC() override {
        usb->chargeWithUSB();
    }
};

int main(){
    int n;
    std::cin >> n;

    for(int i = 0; i < n; ++i){
        TypeC* interface = nullptr;
        int interfaceType;
        std::cin >> interfaceType;
        if(interfaceType == 1){
            interface = new TypeC();
        }else if(interfaceType == 2){
            interface = new Adapter();
        }else{
            std::cout << "Invalid Input!" << std::endl;
            continue;
        }
        interface->chargeWithTypeC();
        delete interface;
    }

    return 0;
}