14 结构性模式-适配器模式
1 适配器模式介绍
适配器模式(adapter pattern )的原始定义是:将类的接口转换为客户期望的另一个接口,适配器可以让不兼容的两个类一起协同工作。
2 适配器模式原理
3 适配器模式应用实例
/**
* SD卡接口
**/
public interface SDCard {
//读取SD卡
String readSD();
//写入SD卡
void writeSD(String msg);
}
/**
* SD卡实现类
**/
public class SDCardImpl implements SDCard {
@Override
public String readSD() {
String msg = "sd card reading data";
return msg;
}
@Override
public void writeSD(String msg) {
System.out.println("sd card write data : " + msg);
}
}
/**
* TF卡接口
**/
public interface TFCard {
//读取TF卡
String readTF();
//写入TF卡
void writeTF(String msg);
}
public class TFCardImpl implements TFCard {
@Override
public String readTF() {
String msg = "tf card reading data";
return msg;
}
@Override
public void writeTF(String msg) {
System.out.println("tf card write data : " + msg);
}
}
/**
* 适配器类(SD兼容TF)
**/
public class SDAdapterTF extends TFCardImpl implements SDCard{
@Override
public String readSD() {
System.out.println("adapter read tf card");
return readTF();
}
@Override
public void writeSD(String msg) {
System.out.println("adapter write tf card");
writeTF(msg);
}
}
/**
* 电脑类
**/
public class Computer {
public String read(SDCard sdCard){
String data = sdCard.readSD();
return data;
}
}
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
SDCard sdCard = new SDCardImpl();
String read = computer.read(sdCard);
System.out.println(read);
System.out.println("=====================");
SDAdapterTF adapterTF = new SDAdapterTF();
System.out.println(computer.read(adapterTF));
}
}
4. 对象适配器模式
/**
* 对象适配器-组合形式
**/
public class SDAdapterTF2 implements SDCard {
private TFCard tfCard;
public SDAdapterTF2(TFCard tfCard) {
this.tfCard = tfCard;
}
@Override
public String readSD() {
System.out.println("adapter read tf card");
return tfCard.readTF();
}
@Override
public void writeSD(String msg) {
System.out.println("adapter write tf card");
tfCard.writeTF(msg);
}
}
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
SDCard sdCard = new SDCardImpl();
System.out.println(computer.read(sdCard));
System.out.println("=======================");
TFCard tfCard = new TFCardImpl();
SDAdapterTF2 adapterTF2 = new SDAdapterTF2(tfCard);
System.out.println(computer.read(adapterTF2));
}
}
5适配器模式总结