装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
InputStream 和 装饰者模式
众人皆知java的输入输出包"java.io"是一个装饰者模式的典型案例,这从下面这个代码就可以大致看出:
Java代码 [url=][/url]
- final BufferInputStream bin =
- new BufferInputStream(new FileInputStream("C:\\test.log"));
但具体是怎样子的还是需要查看JDK源代码:
1. java.io.InputStream == 装饰者模式中的所有类(装饰者和被装饰者)的抽象超类
Java代码 [url=][/url]
- public abstract class InputStream implements Closeable {
- // 定义抽象方法:read
- public abstract int read() throws IOException;
- }
2.java.io.FileInputStream == 具体的被装饰者对象
Java代码 [url=][/url]
- public class FileInputStream extends InputStream {
- public FileInputStream(String name) throws FileNotFoundException {
- this(name != null ? new File(name) : null);
- }
- // 调用本地read方法
- public native int read() throws IOException;
- }
3.java.io.FilterInputStream == 装饰者对象的超类
Java代码 [url=][/url]
- public class FilterInputStream extends InputStream {
- /**
- * The input stream to be filtered.
- */
- protected volatile InputStream in;
-
- protected FilterInputStream(InputStream in) {
- this.in = in;
- }
-
- // 装饰者超类的read方法
- public int read() throws IOException {
- return in.read();
- }
- }
-
-
4.java.io.BufferedInputStream == 具体的装饰者对象
Java代码 [url=][/url]
- public class BufferedInputStream extends FilterInputStream {
-
- public BufferedInputStream(InputStream in) {
- this(in, defaultBufferSize);
- }
-
- public BufferedInputStream(InputStream in, int size) {
- super(in);
- if (size <= 0) {
- throw new IllegalArgumentException("Buffer size <= 0");
- }
- buf = new byte[size];
- }
-
- // 具体装饰者类的read方法
- public synchronized int read() throws IOException {
- if (pos >= count) {
- fill();
- if (pos >= count)
- return -1;
- }
- return getBufIfOpen()[pos++] & 0xff;
- }
- }
|