JDK 1.7 java.io 源码学习之FilterInputStream和FilterOutputStream

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();
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值