适配器模式(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;
}
相关推荐
豆浩宇6 分钟前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
WG_1715 分钟前
C++多态
开发语言·c++·面试
仙魁XAN1 小时前
Unity 设计模式 之 创造型模式-【工厂方法模式】【抽象工厂模式】
unity·设计模式·工厂方法模式·抽象工厂模式
Charles Ray2 小时前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码2 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
迷迭所归处7 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林8 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice9 小时前
2024.9.19
c++
天玑y9 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸2339 小时前
c++ static(详解)
开发语言·c++