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。