适配器模式(Adapter)——结构型模式

适配器模式(Adapter)------结构型模式

什么是适配器模式?

适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作。

举一个经典的"方钉、圆钉、圆孔"问题例子:

适配器假扮成一个圆钉 (Round­Peg), 其半径等于方钉 (Square­Peg) 横截面对角线的一半 (即能够容纳方钉的最小外接圆的半径)。

总结:

圆孔类 只对圆钉类 开放了测试接口,现在方钉类 也想用圆孔类的接口,在不修改圆孔类的前提下,如何修改?

写一个适配器类伪装成(继承)圆钉类,实际内部是方钉类(包含方钉类对象并重写圆钉类方法)。

cpp 复制代码
/*************************************************************************
        > File Name: adapter.cpp
        > Author:
        > Mail:
        > Created Time: Thu Mar 14 10:01:03 2024
 ************************************************************************/

#include <iostream>
#include <cmath>

using namespace std;

class RoundPeg {
private:
    int radius;
public:
    RoundPeg() = default;
    RoundPeg(int r) : radius(r) {}
    virtual int getRadius() {
        return this->radius;
    }
};

class RoundHole {
private:
    int radius;
public:
    RoundHole(int r) : radius(r) {}
    int getRadius() {
        return this->radius;
    }
    bool fits(RoundPeg &peg) {
        return peg.getRadius() <= this->radius;
    }
};

class SquarePeg {
private:
    int width;
public:
    SquarePeg(int w) : width(w) {}
    SquarePeg(const SquarePeg &obj) {
        width = obj.width;
    }
    int getWidth() {
        return this->width;
    }
};

class SquarePegAdapter : public RoundPeg {
private:
    SquarePeg peg;
public:
    SquarePegAdapter(SquarePeg &obj) : peg(obj) {}
    int getRadius() override {
        return peg.getWidth() * sqrt(2) / 2;
    }
};


int main() {
    RoundHole hole(20);

    RoundPeg r_peg1(20);
    RoundPeg r_peg2(21);
    cout << hole.fits(r_peg1) << endl; // 1
    cout << hole.fits(r_peg2) << endl; // 0

    SquarePeg s_peg1(20);
    SquarePeg s_peg2(21);
    SquarePegAdapter s_adapter1(s_peg1);
    SquarePegAdapter s_adapter2(s_peg2);
    cout << hole.fits(s_adapter1) << endl; // 1
    cout << hole.fits(s_adapter2) << endl; // 1

    return 0;
}
相关推荐
Thera7778 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
linux开发之路8 小时前
C++高性能日志库开发实践
c++·c++项目·后端开发·c++新特性·c++校招
刻BITTER9 小时前
在TRAE 上安装PlatformIO
c++·单片机·嵌入式硬件·arduino
永远都不秃头的程序员(互关)9 小时前
C++动态数组实战:从手写到vector优化
c++·算法
水力魔方10 小时前
武理排水管网模拟分析系统应用专题5:模型克隆与并行计算
数据库·c++·算法·swmm
OliverH-yishuihan10 小时前
在win10上借助WSL用VS2019开发跨平台项目实例
linux·c++·windows
汉克老师11 小时前
GESP2025年12月认证C++二级真题与解析(编程题1 (环保能量球))
c++·gesp二级·gesp2级
郝学胜-神的一滴11 小时前
Linux进程与线程控制原语对比:双刃出鞘,各显锋芒
linux·服务器·开发语言·数据结构·c++·程序人生
青岛少儿编程-王老师12 小时前
CCF编程能力等级认证GESP—C++2级—20251227
java·开发语言·c++
javachen__12 小时前
341-十道经典程序设计题目
数据结构·c++·算法