Java IO类库之FilterInputStream与装饰器模式

一、FilterInputStream介绍

/**
 * A <code>FilterInputStream</code> contains
 * some other input stream, which it uses as
 * its  basic source of data, possibly transforming
 * the data along the way or providing  additional
 * functionality. The class <code>FilterInputStream</code>
 * itself simply overrides all  methods of
 * <code>InputStream</code> with versions that
 * pass all requests to the contained  input
 * stream. Subclasses of <code>FilterInputStream</code>
 * may further override some of  these methods
 * and may also provide additional methods
 * and fields.
 *
 * @author  Jonathan Payne
 * @since   JDK1.0
 */
public class FilterInputStream extends InputStream

       由源码中对该类的注释我们可以知道这个类的内部包含其他的输入流成员变量,这个输入流主要用来保存它的基础数据源。该类重写了所有InputStream方法并在方法内部交由成员变量中的基础数据源输入流in去处理,它的作用简单概括就是“封装了其他的数据输入流,供子类扩展他们提供额外的功能”,很容易我们可以想到其中应用了装饰器设计模式思想。

二、FilterInputStream源码分析

package java.io;

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();
    }
}

查看源码可知FilterInputStream类内部引用了一个输入流对象in,各个成员方法只是在方法内部调用了流对象in相应的方法并未做其他处理,FilterInputStream子类封装了其他的输入流并重写了部分方法为输入流提供额外的功能。

三、常用子类

BufferedInputStream

DataInputStream

 

转载于:https://my.oschina.net/zhangyq1991/blog/1854615

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值