C++设计模式浅识适配器模式

来源:这里教程网 时间:2026-02-21 13:12:01 作者:

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

何时使用适配器模式:

两个类所做的事情相同或相似,但是具有不同的接口时需要它。

双方都不太容易修改的时候再使用适配器模式。

模式实现:

[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();
    }
};

客户端:

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

以上就是C++设计模式浅识适配器模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!

相关推荐