FilterInputStream类包含其他一些输入流,它将这些流用作其基本数据源,它可以直接传输数据或提供一些额外的功能。该类本身只是简单地重写那些将所有请求传递给所包含输入流的InputStream 的所有方法。FilterInputStream的子类可进一步重写这些方法中的一些方法,并且还可以提供一些额外的方法和字段。
下面我们直接看看FilterInputStream的源码,就明白该类的实现原理。源码如下:
// 实现了InputStream
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();
}
}从上面可以看出所有提供的方法,如:reset、mark、close、available等方法的实现其实就是调用了FilterInputStream内部InputStream实例的相应方法。这样就可以在原有方法的基础上面提供更强大的功能。如缓存等等。
同时,从代码结构可以看出,这里使用了java设计模式中的装饰模式。装饰(Decorator)模式又名为包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

1、InputStream扮演抽象角色,抽象了所有输入流的操作。
2、FileInputStream实现了InputStream接口,提供了最基本的操作。
3、FilterInputStream实现了InputStream接口,且内部拥有一个FileInputStream类的实例,其中提供了与FileInputStream类一样的接口,每个接口都是使用FileInputStream实例的对应方法进行处理。
4、BufferedInputStream继承了FilterInputStream类,然后对其中需要加强的内进行重写。如:read方法
关于java设计模式相关的信息,请查看模式栏目。