结构型设计模式 - 适配器模式

适配器模式是一种结构型设计模式,它允许将一个类的接口转换成客户端所期待的另一个接口。通常用于使原本由于接口不兼容而不能一起工作的类能够协同工作。

下列适配器模式演示基于经典的 “方钉和圆孔” 问题。
在这里插入图片描述
适配器假扮成一个圆钉 (Round­Peg), 其半径等于方钉 (Square­Peg) 横截面对角线的一半 (即能够容纳方钉的最小外接圆的半径)。

代码示例

圆孔:RoundHole

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.getRadius() >= peg.getRadius());
      return result;
  }
}

圆钉:RoundPeg

public class RoundPeg {
    private double radius;

    public RoundPeg() {}

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

    public double getRadius() {
        return radius;
    }
}

方钉:SquarePeg

public class SquarePeg {
    private double width;

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

    public double getWidth() {
        return width;
    }

    public double getSquare() {
        double result;
        result = Math.pow(this.width, 2);
        return result;
    }
}

方钉到圆孔的适配器:SquarePegAdapter

public class SquarePegAdapter extends RoundPeg {
    private SquarePeg peg;

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

    @Override
    public double getRadius() {
        double result;
        result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
        return result;
    }
}

运行示例:

 public static void main(String[] args) {
        RoundHole roundHole = new RoundHole(5);
        RoundPeg roundPeg = new RoundPeg(5);
        // 圆钉兼容圆孔
        System.out.println(roundHole.fits(roundPeg));

        SquarePeg squarePeg = new SquarePeg(2);
        //方钉不兼容圆孔
        // roundHole.fits(squarePeg);

        // 通过适配器使方钉兼容圆孔
        SquarePegAdapter sqPegAdapter = new SquarePegAdapter(squarePeg);
        System.out.println(roundHole.fits(sqPegAdapter));
    }

优点:

  • 单一职责原则你可以将接口或数据转换代码从程序主要业务逻辑中分离。
  • 符合开闭原则。 只要客户端代码通过客户端接口与适配器进行交互, 你就能在不修改现有客户端代码的情况下在程序中添加新类型的适配器。

缺点:

  • 多使用会增加复杂性: 如果过度使用适配器模式,可能会增加系统的复杂性。
  • 过多适配器类: 当需要适配多个类或接口时,可能需要创建多个适配器类。

适用场景:

  • 接口不兼容:当你希望使用某个类, 但是其接口与其他代码不兼容时, 可以使用适配器类
  • 旧系统升级:当需要复用旧系统中的类而这些类的接口与现有系统的接口不兼容时,可以使用适配器模式。
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值