适配器模式是一种结构型设计模式,通过将一个类的接口转换为客户期望的另一个接口,使得原本接口不兼容的类可以一起工作。适配器模式又称“包装器(Wrapper)”。
特性 | 类适配器 | 对象适配器 |
---|---|---|
实现方式 | 使用继承 | 使用组合 |
适配者数量 | 只能适配一个类 | 可以适配多个适配者 |
灵活性 | 较低,受限于单继承 | 较高,适配器与适配者松耦合 |
扩展性 | 需要创建子类 | 不需要修改适配器类即可扩展 |
现有一个老版本的绘图类 LegacyRenderer
,需要将其适配到新的绘图接口 NewRenderer
,以兼容新功能。
整合多个第三方支付接口(如 PayPal、Stripe)到统一的支付系统中。
将不同厂商的硬件设备接口统一适配为系统标准接口。
#include <iostream>
using namespace std;
// 目标接口
class Target {
public:
virtual void Request() const {
cout << "Target: Default implementation of Request" << endl;
}
virtual ~Target() = default;
};
// 适配者
class Adaptee {
public:
void SpecificRequest() const {
cout << "Adaptee: SpecificRequest called" << endl;
}
};
// 适配器
class Adapter : public Target {
private:
Adaptee* adaptee;
public:
Adapter(Adaptee* adaptee) : adaptee(adaptee) {}
void Request() const override {
adaptee->SpecificRequest();
}
};
// 客户端代码
void ClientCode(const Target* target) {
target->Request();
}
int main() {
cout << "Client: I can work just fine with the Target objects:\n";
Target* target = new Target;
ClientCode(target);
cout << "\nClient: The Adapter makes the Adaptee's interface compatible:\n";
Adaptee* adaptee = new Adaptee;
Target* adapter = new Adapter(adaptee);
ClientCode(adapter);
delete target;
delete adaptee;
delete adapter;
return 0;
}
using System;
// 目标接口
public interface ITarget {
void Request();
}
// 适配者
public class Adaptee {
public void SpecificRequest() {
Console.WriteLine("Adaptee: SpecificRequest called");
}
}
// 适配器
public class Adapter : ITarget {
private readonly Adaptee _adaptee;
public Adapter(Adaptee adaptee) {
_adaptee = adaptee;
}
public void Request() {
_adaptee.SpecificRequest();
}
}
// 客户端代码
class Program {
static void Main(string[] args) {
Console.WriteLine("Client: I can work with Target interface:");
ITarget target = new Adapter(new Adaptee());
target.Request();
}
}
欢迎关注、点赞、收藏!更多系列内容可以点击专栏目录订阅,感谢支持,再次祝大家祉猷并茂,顺遂无虞!
若将文章用作它处,请一定注明出处,商用请私信联系我!