适配器模式(Adapter Pattern)?
结构型模式
适配器模式(或包装模式)是将一个类的接口变换成客户期待的另一种接口,从而使原本因接口不匹配而不能在一起工作的两个类能够在一起工作。
Convert the interface of a class into another interface client expect. Adapter lets class work together that could not otherwise because of incompatible interfaces.
就是 转换器。
UML
- Client: 调用目标类或程序。
- Target: 客户想用的接口。
- Adapter:按照要求对适配对象接口实现接口形式的适配转换。
- Adaptee:需要进行适配的类或对象。
- request:客户端想执行的操作。
- specificRequest:适配对象中能完成request方法功能 的实现。
代码实例
public class AdapterTest {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("d:/AdaptText.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
System.out.println(bufferedReader.readLine());
}
}
是不是感觉很熟?其实InputStreamReader
就是一个Adapter,将Stream字节流转换成字符流
适配器实现
- Adaptee
public class Adaptee {
public void specificRequest(){
//specific方法
}
}
- Target
public interface Target {
public void request();
}
- 适配器Adapter
public class Adapter extends Adaptee implements Target{
@Override
public void request() {
super.specificRequest();
//进行业务处理
}
}
- Cilent用户端
public class Client {
public static void main(String[] args) {
Target target = new Adapter();
target.request();
}
}
总结
对开发维护来讲,该模式增加了一层代码抽象,但如果在不允许重写现有代码的情况下,适配器就该上场了。