适配器模式(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;
}
相关推荐
明洞日记7 小时前
【VTK手册024】高效等值面提取:vtkFlyingEdges3D 详解与实战
c++·图像处理·vtk·图形渲染
遥望九龙湖7 小时前
3.析构函数
开发语言·c++
qq_479875437 小时前
systemd-resolved.service实验实战3
linux·服务器·c++
闻缺陷则喜何志丹7 小时前
【图论 组合数学】P10912 [蓝桥杯 2024 国 B] 数星星|普及+
c++·数学·蓝桥杯·图论
Jeff-Nolan7 小时前
C++运算符重载
java·开发语言·c++
YouEmbedded7 小时前
解码智能指针
开发语言·c++·unique_ptr·shared_ptr·auto_ptr·weak_ptr
神仙别闹7 小时前
基于QT(C++)实现(图形界面)连连看
java·c++·qt
NZT-488 小时前
C++基础笔记(三)链表list
c++·笔记·链表
_Voosk8 小时前
C指针存储字符串为何不能修改内容
c语言·开发语言·汇编·c++·蓝桥杯·操作系统
吃不饱的得可可8 小时前
【Linux】mmap文件映射的使用
linux·开发语言·c++