8.4JavaI/O流之Filter模式

Filter(装饰者:Decorator)模式

用InputStream做例子,该InputStream需要更多的功能,而更多的功能则需要新建一个InputStream的子类来继承inputStream,在此类上添加另一个功能,则需要继续继承新建,以此往复不断新建,会导致代码复杂度变大,子类太多,为解决这种问题,产生了Filter模式。

InputStream file = new FileInputStream("test.gz");//确定数据源
InputStream buffered = new BufferedInputStream(file);//添加缓冲功能
InputStream gzip = new GZIPInputStream(buffered);//添加解压功能

以上就是Filter模式,对源对象进行包装,但无论包装多少次,该对象还是InputStream对象。OutputStream也适用于该模式。

编写FilterInputStream类

FilterInputStream类是一种功能类,并提供给InputStream包装。

class CountInputStream extends FilterInputStream {
    private int count = 0;

    CountInputStream(InputStream in) {
        super(in);
    }

    public int getBytesRead() {
        return this.count;
    }

    public int read() throws IOException {
        int n = in.read();
        if (n != -1) {
            this.count ++;
        }
        return n;
    }

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

以上例子说明了如何创建FilterInputStream。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值