手机跟新迭代迅速,以前的手机都要SD内存卡。第一批手机比如诺基亚手机又用的更古老的TFcard,所以新手机要用旧手机的TF内存卡就要有SD适配TF内存卡适配器。
SD存储卡接口
public interface SDCard {
String readSD();
void writeSD(String msg);
}
SD存储卡实现
public class SDCardImpl implements SDCard{
TFCardImpl tfCard=new TFCardImpl();
@Override
public String readSD() {
String msg="SDCard read data : hello world";
return msg;
}
@Override
public void writeSD(String msg) {
}
}
TF存储卡接口
public interface TFCard {
String read();
void write(String msg);
}
TF存储卡实现
/*
适配者类
*/
public class TFCardImpl implements TFCard{
@Override
public String read() {
String msg="TFCard read data : hello world";
return msg;
}
@Override
public void write(String msg) {
System.out.println("TFCard write msg :"+ msg);
}
}
适配器
适配器有存储卡的功能,但最终实现的时TF内存卡的功能,所以要继承TF内存卡的实现
public class SDAdapterTF extends TFCardImpl implements SDCard{
@Override
public String readSD() {
System.out.println("adapter read TF card");
return read();
}
@Override
public void writeSD(String msg) {
System.out.println("adapter write tf card");
write(msg);
}
}
调用存储卡的电脑类
测试类调用方法即可
/**
* @author Dsmash
*/
public class Computer {
public String readSD(SDCard sdCard){
if (sdCard==null){
throw new NullPointerException("sd card is not null");
}
return sdCard.readSD();
}
}
java中InputSteamReader字符流中有个decoder()方法使用了适配器,它可以将inputstream字节流对象转换为字符流对象,感兴趣可以看源码。