【C++】适配器模式

适配器模式(Adapter Pattern)是一种结构型设计模式,用于解决接口不兼容的问题。当两个原本不兼容的类需要协同工作时,适配器模式通过创建一个中间层(适配器)来转换接口,使它们能够无缝协作。这种模式在遗留系统集成、第三方库对接等场景中尤为常见。

一、模式核心概念与结构

适配器模式包含三个核心角色:

  1. 目标接口(Target):客户端期望的接口。
  2. 适配者(Adaptee):需要被适配的现有接口。
  3. 适配器(Adapter):连接目标接口和适配者的中间层,负责接口转换。

适配器模式有两种实现方式:类适配器(通过继承实现)和对象适配器(通过组合实现)。在 C++ 中,对象适配器更常用,因为它避免了多重继承的复杂性。

二、对象适配器实现示例

以下是一个将圆接口适配为矩形接口的经典示例:

#include <iostream>
#include <cmath>

// 目标接口:客户端期望的矩形接口
class Rectangle 
{
   
public:
    virtual ~Rectangle() {
   }
    virtual void draw(int x, int y, int width, int height) = 0;
};

// 适配者:现有的圆接口
class Circle {
   
public:
    void drawCircle(int x, int y, int radius) 
    {
   
        std::cout << "Drawing circle at (" << x << ", " << y 
                  << ") with radius " << radius << std::endl;
    }
};

// 对象适配器:将圆适配为矩形接口
class CircleAdapter : public Rectangle 
{
   
private:
    Circle circle; // 组合适配者对象

public:
    // 实现目标接口的draw方法,转换为圆的绘制逻辑
    void draw(int x, int y, int width, int height) override 
    {
   
        // 假设矩形的宽高相等时视为圆形(简化逻辑)
        int radius = width / 2;
        if (height == width) 
        {
   
            circle.drawCircle(x + radius, y + radius, radius);
        } else 
        {
   
            std::cout << "Invalid rectangle for circle adaptation" << std::endl;
        }
    }
};

// 客户端代码
int main() 
{
   
    // 使用适配器替代原生矩形接口
    Rectangle* adapter = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OpenC++

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值