c++适配器模式

在这里插入代码片

#include <iostream>
#include <math.h> 
#include <memory>
using namespace std;
// 基础接口:所有能放入圆孔的物体都应该满足一定的条件(如直径)
class RoundPeg {
public:
    // 纯虚函数,返回半径大小
    virtual double getRadius() const = 0;
};

// 具体组件 - 圆形钉
class ConcreteRoundPeg : public RoundPeg {
private:
    double radius;

public:
    // 构造函数初始化圆形钉的半径
    ConcreteRoundPeg(double r) : radius(r) {}

    // 返回当前实例的半径值
    double getRadius() const override { return this->radius; }
};

// 目标接口——圆形孔
class RoundHole {
private:
    double radius;

public:
    // 显式构造函数设置圆形孔的半径
    explicit RoundHole(double rad) : radius(rad) {}
    
    // 判断给定的圆形物品能否穿过本圆孔
    bool fits(const RoundPeg &peg) const {
        // 如果圆柱体的最大宽度不超过圆心到边缘的距离,则认为它可以穿过此圆孔。
        return (peg.getRadius() * 2 <= this->radius);
    }
};

// 方头类:方形钉不能直接放进圆孔中
class SquarePeg {
protected:
    double width_; 

public:
    // 构造函数初始化方形钉的边长
    explicit SquarePeg(double w) : width_(w) {}

    // 获取方形钉的一条边长
    [[nodiscard]] inline double getWidth() const noexcept { return this->width_; }
};

// 创建适配器使方形钉适应已有的系统
class SquarePegAdapter final : public RoundPeg {
private:
    std::unique_ptr<SquarePeg> square_;

public:
    // 使用现有平方钉实例构建适配器
    explicit SquarePegAdapter(std::unique_ptr<SquarePeg> &sp)
            : square_{std::move(sp)} {}

    // 把方形的宽转换成等效直径并作为如果它是来自一个圆形对象一样返回
    double getRadius() const override {
        return sqrt(pow(this->square_->getWidth(), 2) + pow(this->square_->getWidth() / 2., 2)) / 2.;
    }
};

// 测试代码示例


int main() {
    auto h = new RoundHole(10.);          // 创建一个半径为10单位长度的圆形孔
    auto p = make_unique<ConcreteRoundPeg>(5.);  // 创建一个半径为5单位长度的圆形钉

    if (h->fits(*p)) {
        cout << "圆形钉可以插入:" << endl;
    } else {
        cout << "圆形钉无法插入。" << endl;
    }

    auto s = make_unique<SquarePeg>(8);  // 创建一条边长为8单位长度的方形钉
    
    // 不使用适配器的情况下尝试将方形钉插入圆形孔...这会引起错误!

    // 使用适配器!
    auto sa = new SquarePegAdapter(s);   // 创建一个包含方形钉的适配器
   
    if (h->fits(*sa)) {
        cout << "适配后的方形钉可以插入。" << endl;
    } else {
        cout << "即使进行了适配,方形钉仍无法插入。" << endl;
    }

    delete h;
    delete sa;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值