0%

Filter模式

Filter模式


继承的问题

如果新功能的实现依赖于继承(每个新功能对应一个子类)会出现子类数目过多的情况

栗子

  • 给FileInputStream添加解压、签名、加解密

问题的解决

分类是不可或缺的

  • InputStream

    • FileInputStream
    • ByteArrayInputStream
    • ServletInputStream
    • BufferedInputStream
    • DigestInputStream
    • CipherInputStream

先new基础类,再以基础类为参数new额外功能类,但统筹调度统一用InputStream

编写FilterInputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package eternal.fire;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CountInputStream extends FilterInputStream {
private int count = 0;

/**
* Creates a {@code FilterInputStream}
* by assigning the argument {@code in}
* to the field {@code this.in} so as
* to remember it for later use.
*
* @param in the underlying input stream, or {@code null} if
* this instance is to be created without an underlying stream.
*/
public CountInputStream(InputStream in) {
super(in);
}

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

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

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

}