定义:
将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
结构:
目标接口:当前业务所期待的接口,如上图适配器中的二孔插座
适配者类:它是被访问和适配的现存组件库中的组件接口,如上图的壁式插座
适配器类:它是一个转换器,通过继承或引用适配者的对象,把适配者接口转换成目标接口,让客户按目标接口的格式访问适配者。
一、类适配器
【例】读卡器
现有一台电脑只能读取SD卡,而要读取TF卡中的内容的话就需要使用到适配器模式。创建一个读卡器,将TF卡中的内容读取出来。
//目标类
public interface SDCard {
//从SD卡中读取数据
String readSD();
//往SD卡中写数据
void writeSD(String msg);
}
public class SDCardImpl implements SDCard {
public String readSD() {
String msg = "hello word SD";
return msg;
}
public void writeSD(String msg) {
System.out.println("SDCard write msg :" + msg);
}
}
适配者类
//适配者类
public interface TFCard {
//从TF卡中读取数据
String readTF();
//往TF卡中写数据
void writeTF(String msg);
}
public class TFCardImpl implements TFCard {
public String readTF() {
String msg = "TFCard read msg : hello word TFcard";
return msg;
}
public void writeTF(String msg) {
System.out.println("TFCard write msg :" + msg);
}
}
适配器类
public class SDAdapterTF extends TFCardImpl implements SDCard {
public String readSD() {
System.out.println("adapter read tf card");
return readTF();
}
public void writeSD(String msg) {
System.out.println("adapter write tf card");
writeTF(msg);
}
}
public class Computer {
//从SD卡中读取数据
public String readSD(SDCard sdCard) {
if(sdCard == null) {
throw new NullPointerException("sd card is not null");
}
return sdCard.readSD();
}
}
public class Client {
public static void main(String[] args) {
//创建计算机对象
Computer computer = new Computer();
//读取SD卡中的数据
String msg = computer.readSD(new SDCardImpl());
System.out.println(msg);
System.out.println("===============");
//使用该电脑读取TF卡中的数据
//定义适配器类
String msg1 = computer.readSD(new SDAdapterTF());
System.out.println(msg1);
}
}
二、对象适配器模式
它和适配类最大的不同就是适配器的不同,我们只要对适配器进行修改,既可变成对象适配器
public class SDAdapterTF implements SDCard {
//声明适配者类
private TFCard tfCard;
public SDAdapterTF(TFCard tfCard) {
this.tfCard = tfCard;
}
public String readSD() {
System.out.println("adapter read tf card");
return tfCard.readTF();
}
public void writeSD(String msg) {
System.out.println("adapter write tf card");
tfCard.writeTF(msg);
}
}
应用场景:
1、以前开发的系统存在满足新系统功能需求的类,但其接口同新系统的接口不一致。
2、使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同。