设计模式 - 装饰者模式(Decorator Pattern) Java的IO类 使用方法

来源:互联网 发布:东京23区 知乎 编辑:程序博客网 时间:2024/05/16 17:30

装饰者模式(Decorator Pattern) Java的IO类 使用方法


本文地址: http://blog.csdn.net/caroline_wendy/article/details/26716823


装饰者模式(decorator pattern)参见: http://blog.csdn.net/caroline_wendy/article/details/26707033


Java的IO类使用装饰者模式进行扩展, 其中FilterInputStream类, 就是装饰者(decorator)的基类.

实现其他装饰者(decorator), 需要继承FilterInputStream类.


代码:

/** * @time 2014年5月23日 */package decorator.io;import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;/** * @author C.L.Wang * */public class LowerCaseInputStream extends FilterInputStream {public LowerCaseInputStream(InputStream in) {super(in);}public int read() throws IOException {int c = super.read();return (c==-1 ? c : Character.toLowerCase((char)c));}public int read(byte[] b, int offset, int len) throws IOException {int result = super.read(b, offset, len);for (int i=offset; i<offset+result; ++i) {b[i] = (byte)Character.toLowerCase((char)b[i]);}return result;}}

测试:

/** * @time 2014年5月23日 */package decorator.io;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;/** * @author C.L.Wang * */public class InputTest {/** * @param args */public static void main(String[] args) throws IOException{// TODO Auto-generated method stubint c;try{InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("test.txt")));while ((c = in.read()) >= 0) {System.out.print((char)c);}in.close();} catch (IOException e){e.printStackTrace();}}}

通过装饰具体组件类FileInputStream, 实现格式的更改.

注意:Java的文件的默认读取路径为项目的根目录.






9 0