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

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

什么是适配器模式?

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

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

在这里插入图片描述

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

总结:

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

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

/*************************************************************************
        > 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;
}

相关推荐

  1. 设计模式_结构模式_适配器模式

    2024-03-18 07:54:03       31 阅读
  2. 设计模式结构模式适配器模式

    2024-03-18 07:54:03       31 阅读
  3. 适配器模式Adapter

    2024-03-18 07:54:03       45 阅读
  4. 适配器模式 Adapter Pattern

    2024-03-18 07:54:03       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-18 07:54:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-18 07:54:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-18 07:54:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-18 07:54:03       20 阅读

热门阅读

  1. 利用适配器模式使用第三方库

    2024-03-18 07:54:03       22 阅读
  2. 【运维】Ubuntu 安装Scala

    2024-03-18 07:54:03       20 阅读
  3. 数据噪声对数据分析的影响及其应对策略

    2024-03-18 07:54:03       20 阅读
  4. Sass学习记录

    2024-03-18 07:54:03       16 阅读
  5. linux服务器保存git账号密码命令

    2024-03-18 07:54:03       23 阅读
  6. Linux四剑客-find命令学习

    2024-03-18 07:54:03       20 阅读
  7. 设计原则、工厂、单例模式

    2024-03-18 07:54:03       20 阅读
  8. 他山之石可以攻玉

    2024-03-18 07:54:03       19 阅读
  9. 渗透测试基础技能树梳理

    2024-03-18 07:54:03       19 阅读
  10. Keras库搭建神经网络

    2024-03-18 07:54:03       20 阅读