适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作。
适配器假扮成一个圆钉 (RoundPeg), 其半径等于方钉 (SquarePeg) 横截面对角线的一半 (即能够容纳方钉的最小外接圆的半径),下面给出模式结构和伪代码。
//假设你有两个接口相互兼容的类:圆孔(RoundHole)和圆钉(RoundPeg)。
class RoundHole is
constructor RoundHole(radius) { ... }
method getRadius() is
// 返回孔的半径。
method fits(peg: RoundPeg) is
return this.getRadius() >= peg.radius()
class RoundPeg is
constructor RoundPeg(radius) { ... }
method getRadius() is
// 返回钉子的半径。
// 但还有一个不兼容的类:方钉(SquarePeg)。
class SquarePeg is
constructor SquarePeg(width) { ... }
method getWidth() is
// 返回方钉的宽度。
// 适配器类让你能够将方钉放入圆孔中。它会对 RoundPeg 类进行扩展,以接收适
// 配器对象作为圆钉。
class SquarePegAdapter extends RoundPeg is
// 在实际情况中,适配器中会包含一个 SquarePeg 类的实例。
private field peg: SquarePeg
constructor SquarePegAdapter(peg: SquarePeg) is
this.peg = peg
method getRadius() is
// 适配器会假扮为一个圆钉,
// 其半径刚好能与适配器实际封装的方钉搭配起来。
return peg.getWidth() * Math.sqrt(2) / 2
// 客户端代码中的某个位置。
hole = new RoundHole(5)
rpeg = new RoundPeg(5)
hole.fits(rpeg) // true
small_sqpeg = new SquarePeg(5)
large_sqpeg = new SquarePeg(10)
hole.fits(small_sqpeg) // 此处无法编译(类型不一致)。
small_sqpeg_adapter = new SquarePegAdapter(small_sqpeg)
large_sqpeg_adapter = new SquarePegAdapter(large_sqpeg)
hole.fits(small_sqpeg_adapter) // true
hole.fits(large_sqpeg_adapter) // false
SquarePegAdapter(适配器)继承了的RoundPeg(圆钉),重写了父类的getRadius()方法,当父类指针指向子类时,调用getRadius()方法,此时会调用适配器的getRadius()方法,利用了多态机制。
适配器实现了其中一个对象的接口, 并对另一个对象进行封装。 它在实现客户端接口的同时封装了服务对象。 适配器接受客户端通过适配器接口发起的调用, 并将其转换为适用于被封装服务对象的调用。适配器模式允许你创建一个中间层类, 其可作为代码与遗留类、 第三方类或提供怪异接口的类之间的转换器。还以扩展每个子类, 将缺少的功能添加到新的子类中。
圆钉、方钉、圆孔有各自属性和方法,内聚度高,耦合度低,适配器继承圆孔,与圆孔耦合度高,与其他耦合度低。
参见https://github.com/yingjiehuangs/adapterModel
原文:https://www.cnblogs.com/yingjiehuang/p/11986363.html