FilterInputStream和FilterOutputStream 就是 java.io 中其他功能扩展实现类的父类,其中的设计模式是装饰者模式。
装饰者模式:在不改变原类文件和不使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
当然了,上述UML中是可以变形的:
1. Component可以是抽象类,或者普通类(不建议)
2. Decorator也并不是一定是必须的
java.io 输入流的装饰模式结构:
java.io 输出流的装饰模式结构:
FilterInuptStream和FilterOutputStream 实际非常简单,就是内部持有了一个对象,InputStream或者OutputStream,所有的方法都是对InputStream和OutputStream方法的一次封装调用
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();
}
}
public class FilterOutputStream extends OutputStream {
protected OutputStream out;
public FilterOutputStream(OutputStream out) {
this.out = out;
}
public void write(int b) throws IOException {
out.write(b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
throw new IndexOutOfBoundsException();
for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
}