Okio in Action

Okio是由Square公司开源的一个库,它宣称补充了java.io和java.nio的不足,使得我们更加方便,快速访问,存储和处理你的数据。我在它的主要作者Jesse Wilson在他的git initial commit里看到了他写这个库的初衷:

I'm unhappy with java.io:
* No timeouts.
* Every layer needs to copy bytes around. Always copying bytes.
* Features like mark/reset and available() are clumsy.
* Its awkard in mixed text/binary protocols like HTTP because character decoding is separate and takes over the stream.

Unfortunately java.nio isn't better, just different:
* It's complex.
* Buffers are fixed size.
* No built-in buffer pooling.
* Features like mark/reset/position are clumsy.

This is an obnoxious attempt at a 3rd I/O interface, mostly inspired by InputStream and OutputStream, but using growable
buffers instead of byte arrays as the core data container.

Okio非常小巧,代码量相对那些动辄几万行的库,堪称蝇级。我觉得是一个非常适合用来学习的开源项目。本文旨在分析一下Okio的架构和一些主要的接口和设计。

Okio中有两个关键的接口, SinkSource, 这两个接口都继承了Closeable接口,Sink还继承了Flushable接口。Sink可以简单地看作OutputStream, Source可以简单地看作InputStream,这两个接口都是支持读写超时设置的。

它们各自有一个支持缓冲区的子类接口,BufferedSink和BufferedSource,而BufferedSink有一个实现类RealBufferedSink, BufferedSource有一个实现类RealBufferedSource; 此外,Sink和Source它们还各自有一个支持Gzip压缩的实现类GzipSink和GzipSource;一个具有委托功能的抽象类ForwardingSink和ForwardingSource,这两个抽象类又各自有一个子类HashingSink和HashingSource还各有一个实现类InflaterSource和DeflaterSink,这两个类主要用于压缩,为GzipSink和GzipSource服务,整体的结构图如下:

TO BE CONTINUED.....

comments powered by Disqus