前言
之前的博客说到了适配器模式的概念和UML类图,这次来聊下IO中的适配器模式。
正文
IO流体系介绍
InputStreamReader 和OutputStreamWriter 类分别继承了Reader和Writer 接口,但是要创建它们的对象必须在构造函数中传入一个InputStream和OutputStream的实例,InputStreamReader和OutputStreamWriter 的作用 是将InputStream和OutputStream 适配到Reader和Writer。
下面是InputStreamReader的类结构:
这里的适配器角色就是InputStreamReader,被适配的角色是InputStream类代笔的实例对象,目标接口是Reader类。
可以看到,InputStreamReader实现了Reader接口,并且持有了InputStream的引用,这里是通过StreamDecoder类间接持有的,因为从byte到char 要经过编码。
源码浅析
/******************Reader类(目标类)******************/
package java.io;
public abstract class Reader implements Readable, Closeable {
abstract public int read(char cbuf[], int off, int len) throws IOException;
abstract public void close() throws IOException;
}
/******************InputStreamReader类(适配器类)******************/
public class InputStreamReader extends Reader {
private final StreamDecoder sd;
//持有对被适配对象的引用
public InputStreamReader(InputStream in) {
super(in);
try {
//通过StreamDecoder类间接引用被适配的对象
sd = StreamDecoder.forInputStreamReader(in, this, (String)null);
} catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
public InputStreamReader(InputStream in, String charsetName)
throws UnsupportedEncodingException
{
super(in);
if (charsetName == null)
throw new NullPointerException("charsetName");
sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
}
public InputStreamReader(InputStream in, Charset cs) {
super(in);
if (cs == null)
throw new NullPointerException("charset");
sd = StreamDecoder.forInputStreamReader(in, this, cs);
}
public int read(char cbuf[], int offset, int length) throws IOException {
return sd.read(cbuf, offset, length);
}
public void close() throws IOException {
sd.close();
}
//…(省略的代码)
}
/******************InputStream类(被适配类)******************/
public abstract class InputStream implements Closeable {
//代码省略
}
使用Demo
File file = new File("hello.txt");
FileInputStream in = new FileInputStream(file);
// 将FileInputStream适配成InputStreamReader,即输入的字节流转换成字符流
InputStreamReader inReader = new InputStreamReader(in);
总结
适配器在IO中的应用就介绍到这里了,感谢您的耐心阅读!