适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
何时使用适配器模式:
- 两个类所做的事情相同或相似,但是具有不同的接口时需要它。
- 双方都不太容易修改的时候再使用适配器模式。
模式实现:
//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
int main(){
Target *targetObj = new Adapter();
targetObj->Request(); //Output: Adaptee::SpecificRequest
delete targetObj;
targetObj = NULL;
return 0;
}
本文介绍了适配器模式(Adapter),一种使原本接口不兼容的类能够协同工作的设计模式。通过具体的C++代码示例,展示了如何创建适配器类来连接目标接口与适配者接口。
1564

被折叠的 条评论
为什么被折叠?



