适配器模式(Adapter Pattern)把一个类的接口变换成客户端期待的另一种接口,从而是原本因接口不匹配而无法一起工作的两个类能够一起工作。
适配器模式有两种不同形式
类的适配器模式把被适配的类的API转换成目标类的API,
其静态结构如下:
在上图可以看出,Adaptee类并没有 sampleOperation2() 方法,而客户端则期待这个方法。
为使客户端能够使用 Adaptee 类,提供一个中间环节,即类 Adapter, 把 Adaptee 的API与 Target 类API 衔接起来。Adapter 与 Adaptee 是继承关系,这决定了这个适配器模式是类的。
模式涉及的角色:
示意性代码清单:
Target的源代码
package com.vincent.shipei;
public interface Target {
/**
* 这是源类也有的方法
*/
void sampleOperation1();
/**
* 这是源类没有的方法
*/
void sampleOperation2();
}
Adaptee的源码
package com.vincent.shipei;
public class Adaptee {
/**
* 源类含有的方法
*/
public void sampleOperation1(){}
}
Adapter的源代码
package com.vincent.shipei;
public class Adapter extends Adaptee implements Target {
/**
* 由于源类没有方法 sampleOperation2,
* 因此适配器类补充上这个方法
*/
@Override
public void sampleOperation2() {
//write your code here
}
}
适配器角色 Adapter扩展了Adaptee,同时又实现了目标接口。
类的适配器模式的效果
使用一个具体类把源(Adaptee)适配到目标(Target)中。这样一来,如果源以及源的子类都使用此类适配,就行不通了。
由于之引进了一个适配器类,因此只有一个路线到达目标类,是问题得到简化。
与类的适配器模式一样,对象的适配器模式把适配的类的API转换成为目标类的API,
与类的适配器模式不同的是,对象的适配器模式不是使用继承关系连接到 Adaptee类,
而是使用委派关系连接到 Adaptee类。
对象的适配器模式结构如下:
角色如下:
示意源码
Target的源代码
package com.vincent.shipei;
public interface Target {
/**
* 这是源类也有的方法
*/
void sampleOperation1();
/**
* 这是源类没有的方法
*/
void sampleOperation2();
}
Adaptee的源代码
package com.vincent.shipei;
public class Adaptee {
/**
* 源类含有的方法
*/
public void sampleOperation1(){}
}
Adapter的源代码
package com.vincent.shipei;
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
super();
this.adaptee = adaptee;
}
@Override
public void sampleOperation1() {
adaptee.sampleOperation1();
}
@Override
public void sampleOperation2() {
//write your code here
}
}
对象适配器模式的效果:
从Iterator到 Enumeration的适配
从Enumeration到 Iterator的适配
JDBC驱动软件与适配器模式
每一个数据库引擎的JDBC驱动软件都是一个介于JDBC接口和数据库引擎接口直接的适配器软件。
如下图