适配器模式

阅读文章:https://refactoringguru.cn/design-patterns/adapter

一、解决了什么问题

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

在这里插入图片描述

二、不使用此设计模式会出现什么情况

无法将不兼容的对象进行相互合作

三、符合什么原则

1、通过适配器做到可插拔,同时不影响现有的结构保持开闭原则

**开闭原则:**对扩展开放,对修改关闭

2、单一职责原则:可以将接口或数据转换代码从程序主要业务逻辑中分离

**单一职责原则:**一个类只负责一项职责

四、代码实现

例子:让方钉适配圆孔

圆钉:

public class RoundPeg {

    private  double radius;

    public RoundPeg() {}

    public RoundPeg(double radius) {
        this.radius  = radius;
    }

    public double getRadius() {
        return radius;
    }
}

方钉:

public class SquarePeg {

    private double width;

    public SquarePeg(double width) {
        this.width = width;
    }

    public double getWidth() {
        return width;
    }

}

圆孔:

public class RoundHole {

    private double radius;

    public RoundHole(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public boolean fits(RoundPeg peg) {
        boolean result;
        //圆孔是否适合圆钉
        result = (this.radius >= peg.getRadius());
        return result;
    }

}

方钉适配器:

public class SquarePegAdapter extends RoundPeg{

    private SquarePeg squarePeg;

    public SquarePegAdapter(SquarePeg squarePeg) {
        this.squarePeg = squarePeg;
    }

    //重写圆钉获取的数据的方法
    @Override
    public double getRadius() {
        double result;
        result = Math.sqrt(Math.pow((squarePeg.getWidth() / 2),2) * 2);
        return result;
    }
}

测试:

public class AdapterTest {

    public static void main(String[] args) {

        RoundHole hole = new RoundHole(5);
        RoundPeg roundPeg = new RoundPeg(5);
        if (hole.fits(roundPeg)) {
            System.out.println("圆孔圆钉配对成功");
        }

        SquarePeg smallPeg = new SquarePeg(2);
        SquarePeg largePeg = new SquarePeg(20);

        SquarePegAdapter smallPegAdapter = new SquarePegAdapter(smallPeg);
        SquarePegAdapter largePegAdapter = new SquarePegAdapter(largePeg);

        if (hole.fits(smallPegAdapter)) {
            System.out.println("圆孔方钉配对成功");
        }
        if (!hole.fits(largePegAdapter)) {
            System.out.println("圆孔方钉配对失败");
        }

    }

}
"圆孔方钉配对成功");
        }
        if (!hole.fits(largePegAdapter)) {
            System.out.println("圆孔方钉配对失败");
        }

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默默行路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值