Java流中的装饰者模式

1.介绍

上一节我们说Java.io.FilterInputStream/FilterOutputStream是装饰者类, 那么哪些又是可被包装的类,哪些又是包装类呢?

2.可被包装类

java.io.FileInputStream
java.io.StringBufferInputStream
java.io.ByteArrayInputStream
...
可基本上说,直接继承InputStream(FilterInputStream除外),都是可被包装类

3.包装类

java.io.BufferedInputStream
java.io.LineNumberInputStream
...
可基本上说,FilterInputStream子类,都是包装类

4.小栗子(使用已经有的包装类)

InputStream inputStream = new BufferedInputStream(new FileInputStream(new File()));

5.自定义包装类(大写字母转成小写字母),小栗子

5.1 LowerCaseInputStream.java自定义包装类
public class LowerCaseInputStream extends FilterInputStream {
    protected LowerCaseInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        int read = super.read();
        if (read != -1) {
            read = Character.toLowerCase((char) read);
        }
        return read;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int result = super.read(b, off, len);
        for (int index = off; index < off + len; index ++) {
            b[index] = (byte) Character.toLowerCase((char) b[index]);
        }
        return result;
    }
}
5.2 测试
public class DecoratorStreamDemo {
    public static void main(String[] args) {
        String filePath = "C:/MineProjects/JavaDemo/src/main/java/tt.txt";
        InputStream inputStream = null;
        try {
            inputStream = new LowerCaseInputStream(
                    new FileInputStream(
                            new File(filePath)));
            StringBuilder sb = new StringBuilder();
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1) {
                sb.append(new String(bytes, 0, len));
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

6.总结

流这一块东西相对来说还是挺多的,字节流/字符流,输入流/输出流,管道流等等。个人观点,先看继承结构,再看设计模式,最后看具体API。

你可能感兴趣的:(Java流中的装饰者模式)