《设计模式的艺术》 刘伟 著 读书笔记
例子:你的伙伴已经根据接口
public interface Algorithms {
void sort(int[] arr);
}
编程了,你找到了一个高效的sort方法,但你没有源代码,只知道方法名和参数列表。
public void quickSort(int[] array){
...
}
这时候就需要适配器了
public interface Algorithms {
void sort(int[] arr);
}
public class MyAlgorithms {
public void quickSort(int[] arr){
}
}
public class Adapter implements Algorithms {
@Override
public void sort(int[] arr) {
MyAlgorithms myAlgorithms=new MyAlgorithms();
myAlgorithms.quickSort(arr);
}
}
当client类已经对接口Algorithms开始编程,而你想重用MyAlgorithms方法(没有源代码,不能copy),不想再实现一次的话,就加入一个适配器Adapter
拓展的还有双向适配器,缺省适配器(当不需要实现一个接口的所有方法,可先设计一个抽象类实现该接口,并提供默认实现,子类可选择性地覆盖父类某些方法来实现需求。这也成为单接口适配器模式)
该设计模式适用场景:
- 系统需要使用一些现有的类,而这些类的接口(例如方法名)不符合系统的需求,甚至没有这些类的源代码。
- 想创建一个可以重复使用的类,用于与一些彼此之间没有太大关联的类,包括一些可能在将来引进的类一起工作。