- 概述
java.io类库封装了操作系统底层的I/O细节,提供一套简单方便、功能丰富的I/O解决方案。但是包含了太多的小类,如果对java.io类库的设计思路不了解,可能会搞不懂java里面的I/O关系。上一节已经介绍了装饰者模式的工作原理,如果我们知道java.io类库是使用装饰者模式组织的,理解起来会简单一些,下面以输入流(其它流基本相似)为例介绍。 UML
说明:
1) InputStream是一个抽象组件。
2) FilterInputStream是一个抽象装饰者。
3) 其它继承自InputStream的类是可以被装饰者包装的具体组件。
4) 继承自FilterInputStream的类是具体的装饰者实现
使用java.io类库,编写一个输入流装饰者示例,实现把输入流内的所有大写字符转成小写。
/**
* 装饰者类-新的输入流装饰者
*/
public class LowerCaseInputStream extends FilterInputStream {
protected LowerCaseInputStream(InputStream in) {
super(in);
}
public int read() throws IOException {
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char) c));
}
}
/**
* 测试类-新的输入流装饰者
*/
public class IODecoratorTest {
public static void main(String[] args) throws IOException {
int c = 0;
// test.txt的内容:LowerCaseInputStream
InputStream in =
new LowerCaseInputStream(
new BufferedInputStream(
new FileInputStream("D:\\temp\\test.txt")));
while ((c = in.read()) >= 0) {
System.out.print((char) c);
}
in.close();
}
}
运行结果:
参考资料:
《Head First设计模式》