JavaIO之装饰器模式

JavaIO之装饰器模式

一、奇怪的JavaIO用法

在我初学 Java 的时候,曾经对 Java IO 的一些用法产生过很大疑惑,比如下面这样一段代码。我们打开文件 test.txt,从中读取数据。其中,InputStream 是一个抽象类,FileInputStream 是专门用来读取文件流的子类。BufferedInputStream 是一个支持带缓存功能的数据读取类,可以提高数据读取的效率。

1
2
3
4
5
6
InputStream in = new FileInputStream("/user/wangzheng/test.txt");
InputStream bin = new BufferedInputStream(in);
byte[] data = new byte[128];
while (bin.read(data) != -1) {
//...
}

初看上面的代码,我们会觉得 Java IO 的用法比较麻烦,需要先创建一个 FileInputStream 对象,然后再传递给 BufferedInputStream 对象来使用。我在想,Java IO 为什么不设计一个继承 FileInputStream 并且支持缓存的 BufferedFileInputStream 类呢?这样我们就可以像下面的代码中这样,直接创建一个 BufferedFileInputStream 类对象,打开文件读取数据,用起来岂不是更加简单?

1
2
3
4
5
InputStream bin = new BufferedFileInputStream("/user/wangzheng/test.txt");
byte[] data = new byte[128];
while (bin.read(data) != -1) {
//...
}

二、基于继承的设计方案

如果 InputStream 只有一个子类 FileInputStream 的话,那我们在 FileInputStream 基础之上,再设计一个孙子类 BufferedFileInputStream,也算是可以接受的,毕竟继承结构还算简单。但实际上,继承 InputStream 的子类有很多。我们需要给每一个 InputStream 的子类,再继续派生支持缓存读取的子类。

除了支持缓存读取之外,如果我们还需要对功能进行其他方面的增强,比如下面的 DataInputStream 类,支持按照基本数据类型(int、boolean、long 等)来读取数据。

1
2
3
FileInputStream in = new FileInputStream("/user/wangzheng/test.txt");
DataInputStream din = new DataInputStream(in);
int data = din.readInt();

在这种情况下,如果我们继续按照继承的方式来实现的话,就需要再继续派生出 DataFileInputStream、DataPipedInputStream 等类。如果我们还需要既支持缓存、又支持按照基本类型读取数据的类,那就要再继续派生出 BufferedDataFileInputStream、BufferedDataPipedInputStream 等 n 多类。这还只是附加了两个增强功能,如果我们需要附加更多的增强功能,那就会导致组合爆炸,类继承结构变得无比复杂,代码既不好扩展,也不好维护。

三、基于装饰器模式的设计方案

针对刚刚的继承结构过于复杂的问题,我们可以通过将继承关系改为组合关系来解决。下面的代码展示了 Java IO 的这种设计思路。不过,我对代码做了简化,只抽象出了必要的代码结构,如果你感兴趣的话,可以直接去查看 JDK 源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public abstract class InputStream {
//...
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}

public int read(byte b[], int off, int len) throws IOException {
//...
}

public long skip(long n) throws IOException {
//...
}

public int available() throws IOException {
return 0;
}

public void close() throws IOException {}

public synchronized void mark(int readlimit) {}

public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}

public boolean markSupported() {
return false;
}
}

public class BufferedInputStream extends InputStream {
protected volatile InputStream in;

protected BufferedInputStream(InputStream in) {
this.in = in;
}

//...实现基于缓存的读数据接口...
}

public class DataInputStream extends InputStream {
protected volatile InputStream in;

protected DataInputStream(InputStream in) {
this.in = in;
}

//...实现读取基本类型数据的接口
}

看了上面的代码,你可能会问,那装饰器模式就是简单的“用组合替代继承”吗?当然不是。从 Java IO 的设计来看,装饰器模式相对于简单的组合关系,还有两个比较特殊的地方。

==第一个比较特殊的地方是:装饰器类和原始类继承同样的父类,这样我们可以对原始类“嵌套”多个装饰器类。==比如,下面这样一段代码,我们对 FileInputStream 嵌套了两个装饰器类:BufferedInputStream 和 DataInputStream,让它既支持缓存读取,又支持按照基本数据类型来读取数据。

1
2
3
4
InputStream in = new FileInputStream("/user/wangzheng/test.txt");
InputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
int data = din.readInt();

==第二个比较特殊的地方是:装饰器类是对功能的增强,这也是装饰器模式应用场景的一个重要特点。==实际上,符合“组合关系”这种代码结构的设计模式有很多,比如代理模式、桥接模式,还有现在的装饰器模式。尽管它们的代码结构很相似,但是每种设计模式的意图是不同的。就拿比较相似的代理模式和装饰器模式来说吧,代理模式中,代理类附加的是跟原始类无关的功能,而在装饰器模式中,装饰器类附加的是跟原始类相关的增强功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 代理模式的代码结构(下面的接口也可以替换成抽象类)
public interface IA {
void f();
}
public class A impelements IA {
public void f() { //... }
}
public class AProxy implements IA {
private IA a;
public AProxy(IA a) {
this.a = a;
}

public void f() {
// 新添加的代理逻辑
a.f();
// 新添加的代理逻辑
}
}

// 装饰器模式的代码结构(下面的接口也可以替换成抽象类)
public interface IA {
void f();
}
public class A implements IA {
public void f() { //... }
}
public class ADecorator implements IA {
private IA a;
public ADecorator(IA a) {
this.a = a;
}

public void f() {
// 功能增强代码
a.f();
// 功能增强代码
}
}

实际上,如果去查看 JDK 的源码,你会发现,BufferedInputStream、DataInputStream 并非继承自 InputStream,而是另外一个叫 FilterInputStream 的类。那这又是出于什么样的设计意图,才引入这样一个类呢?

我们再重新来看一下 BufferedInputStream 类的代码。InputStream 是一个抽象类而非接口,而且它的大部分函数(比如 read(byte b[])、available())都有默认实现,按理来说,我们只需要在 BufferedInputStream 类中重新实现那些需要增加缓存功能的函数就可以了,其他函数继承 InputStream 的默认实现。但实际上,这样做是行不通的。

对于即便是不需要增加缓存功能的函数来说,BufferedInputStream 还是必须把它重新实现一遍,简单包裹对 InputStream 对象的函数调用。具体的代码示例如下所示。==如果不重新实现,那 BufferedInputStream 类就无法将最终读取数据的任务,委托给传递进来的 InputStream 对象来完成。==

1
2
3
4
5
6
7
8
9
10
11
12
public class BufferedInputStream extends InputStream {
protected volatile InputStream in;

protected BufferedInputStream(InputStream in) {
this.in = in;
}

// f()函数不需要增强,只是重新调用一下InputStream in对象的f()
public void f() {
in.f();
}
}

实际上,DataInputStream 也存在跟 BufferedInputStream 同样的问题。为了避免代码重复,Java IO 抽象出了一个装饰器父类 FilterInputStream,代码实现如下所示。InputStream 的所有的装饰器类(BufferedInputStream、DataInputStream)都继承自这个装饰器父类。==这样,装饰器类只需要实现它需要增强的方法就可以了,其他方法继承装饰器父类的默认实现。==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// FilterInputStream类本身只是用将所有请求传递到所包含的输入流来重写InputStream的所有方法。 
// FilterInputStream的子类可以进一步重写其中一些方法,并且还可以提供其他方法和字段。
public class FilterInputStream extends InputStream {
protected volatile InputStream in;

protected FilterInputStream(InputStream in) {
this.in = in;
}

public int read() throws IOException {
return in.read();
}

public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}

public int read(byte b[], int off, int len) throws IOException {
return in.read(b, off, len);
}

public long skip(long n) throws IOException {
return in.skip(n);
}

public int available() throws IOException {
return in.available();
}

public void close() throws IOException {
in.close();
}

public synchronized void mark(int readlimit) {
in.mark(readlimit);
}

public synchronized void reset() throws IOException {
in.reset();
}

public boolean markSupported() {
return in.markSupported();
}
}

到这里,我们已经知道为了给InputStream子类增强功能,我们使用装饰器设计模式,组合代替继承,并且可以对原始类嵌套多个装饰器。下面,我们着重查看装饰器类BufferedInputStream的源代码。

四、BufferedInputStream类剖析

BufferedInputStream向另一个字节输入流添加功能,即缓冲输入并支持mark和reset方法的能力。创建BufferedInputStream时,会创建一个内部缓冲区数组。当读取或跳过流中的字节时,内部缓冲区会根据需要从包含的输入流中重新填充,一次填充多个字节。mark操作会记住输入流中的一个点,而reset操作会导致在从所包含的输入流中获取新字节之前重新读取自最近的mark操作以来读取的所有字节。

1.BufferedInputStream类的字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 默认缓冲区大小
private static int DEFAULT_BUFFER_SIZE = 8192;
// 分配的数组的最大大小。一些虚拟机在数组中保留一些头字,尝试分配更大的数组可能会导致OutOfMemoryError,即请求的数组大小超出VM限制
private static int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
// unsafe类实例
private static final Unsafe U = Unsafe.getUnsafe();
// buf字段的内存偏移量
private static final long BUF_OFFSET
= U.objectFieldOffset(BufferedInputStream.class, "buf");
// 存储数据的内部缓冲区数组。必要时,可以将其替换为另一个不同大小的数组。
protected volatile byte[] buf;
// 该索引比缓冲区中最后一个有效字节的索引大1。该值始终在0到buf.length范围内;元素buf[0]到buf[count-1]包含从底层输入流获得的缓冲输入数据。
protected int count;
// 缓冲区中的当前位置。这是要从buf数组中读取的下一个字符的索引。
// 该值始终在0到count范围内。如果它小于count,则buf[pos]是要作为输入提供的下一个字节;如果它等于count,则下一个read或skip操作将需要从包含的输入流中读取更多字节。
protected int pos;
// 我们先忽略mark方法和reset方法的影响
protected int markpos = -1;
protected int marklimit;

2.BufferedInputStream类的构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 创建BufferedInputStream并将其参数(即输入流)保存in以供以后使用。创建内部缓冲区数组并将其存储在buf中。
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}

// 创建具有指定缓冲区大小的BufferedInputStream,并将其参数(即输入流)保存in以供以后使用。创建长度为size的内部缓冲区数组并将其存储在buf中。
public BufferedInputStream(InputStream in, int size) {
// 调用父类FilterInputStream的构造方法
super(in);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}

3.BufferedInputStream类的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 返回内部实际输入流
private InputStream getInIfOpen() throws IOException {
InputStream input = in;
if (input == null)
throw new IOException("Stream closed");
return input;
}

// 返回内部缓冲数组
private byte[] getBufIfOpen() throws IOException {
byte[] buffer = buf;
if (buffer == null)
throw new IOException("Stream closed");
return buffer;
}

// 详见InputStream的read()方法规约
public synchronized int read() throws IOException {
// 若有效字节已读取完
if (pos >= count) {
// 读取字节填充缓冲数组
fill();
// 实际内部输入流的read方法返回-1,说明到达流末尾,返回-1
if (pos >= count)
return -1;
}
// 有效字节尚未读完,继续读取
return getBufIfOpen()[pos++] & 0xff;
}

// fill方法中我们先忽略mark和reset方法的影响,下面是简化版的内容
private void fill() throws IOException {
// 获取缓冲数组,同时检查输入流是否已经关闭
byte[] buffer = getBufIfOpen();
// pos重置为0
pos = 0;
// count重置为0
count = pos;
// 读取填充缓冲数组的实际字节数
int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
// 更新有效字节数count
if (n > 0)
count = n + pos;
}

// 关闭此输入流并释放与该流关联的所有系统资源。一旦流被关闭,进一步的read()、available()、reset()或skip()调用将抛出IOException。关闭之前已关闭的流没有任何效果。
public void close() throws IOException {
byte[] buffer;
// 自旋+CAS关闭输入流是必要的,因为close方法可以异步发生
while ( (buffer = buf) != null) {
// CAS修改缓冲数组为null
if (U.compareAndSetObject(this, BUF_OFFSET, buffer, null)) {
InputStream input = in;
// 帮助GC
in = null;
// 关闭内部实际输入流
if (input != null)
input.close();
return;
}
// Else retry in case a new buf was CASed in fill()
}
}