课程大纲 / Lesson 10
Adapter 结构型

Adapter · 适配器

将一个类的接口转换成客户端所期望的另一种接口,使原本接口不兼容的类可以一起工作。

01

理解适配器模式:让不兼容的接口能够合作,将已有类的接口转换为目标接口

02

掌握类适配器(继承)与对象适配器(组合)两种实现方式的区别

03

理解适配器模式与门面模式的区别:适配器转换接口,门面简化接口

04

了解适配器在遗留代码集成、第三方库适配、数据格式转换中的应用

核心概念
接口转换类适配器与对象适配器兼容旧代码Wrapper 包装
classDiagram class roundhole { -r int +roundhole(r int) +fits(peg roundpeg) boolean } class roundpeg { -r int +roundpeg(r int) +getradius() int } class squarepeg { -w int +squarepeg(w int) +getwidth() int } class squarepegadapter { -peg squarepeg +squarepegadapter(w int) } roundhole ..> roundpeg roundpeg <|-- squarepegadapter squarepegadapter *-- squarepeg

适配器将 squarepeg 的接口转换为客户端期望的 roundpeg 接口

点击 Run 测试方钉适配...
/** 圆孔:只接受圆榫(RoundPeg)*/
public class RoundHole {
    private int r;

    public RoundHole(int r) { this.r = r; }

    public boolean fits(RoundPeg peg) {
        return this.r >= peg.getRadius();
    }
}
/** 圆榫:可以被圆孔接受 */
public class RoundPeg {
    private int r;

    public RoundPeg(int r) { this.r = r; }

    public int getRadius() { return r; }
}
/** 方榫:接口与 RoundPeg 不兼容(提供 getWidth 而非 getRadius)*/
public class SquarePeg {
    private int w;

    public SquarePeg(int w) { this.w = w; }

    public int getWidth() { return w; }
}
/** 对象适配器:持有 SquarePeg,将 getWidth() 适配为 getRadius() */
public class SquarePegAdapter extends RoundPeg {
    private SquarePeg peg;

    public SquarePegAdapter(int w) {
        super(int)(w * Math.sqrt(2) / 2);
        this.peg = new SquarePeg(w);
    }
}
public class Demo {
    public static void main(String[] args) {
        RoundHole hole = new RoundHole(5);
        RoundPeg rpeg = new RoundPeg(5);
        SquarePegAdapter adapt = new SquarePegAdapter(5);

        System.out.println("RoundHole(r=5) fits RoundPeg(r=5): "
            + hole.fits(rpeg));
        System.out.println("RoundHole(r=5) fits SquarePegAdapter: "
            + hole.fits(adapt));
    }
}
◈

适配器解决接口不兼容

SquarePegAdapter 通过继承 RoundPeg 并持有 SquarePeg,将方钉的 getWidth() 转换为 getRadius(),使方钉能适配圆孔。

◈

类适配器 vs. 对象适配器

类适配器(继承):SquarePegAdapter extends RoundPeg;对象适配器(组合):SquarePegAdapter 持有 SquarePeg。对象适配器更灵活,可适配被适配者的子类。

◈

适配器 vs. 门面 vs. 装饰器

适配器:转换接口(让不兼容变兼容);门面:简化接口(降低复杂度);装饰器:增加功能(动态增强)。

◈

典型应用场景

集成遗留系统(适配旧接口)、第三方库(统一不同 SDK 的接口)、数据格式转换(XML→JSON)、日志框架统一接口。