装饰者模式--java io
2016-01-28 18:02
639 查看
import java.io.FileInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; //转化为小写 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(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; } } public class Main { public static void main(String[] args) throws IOException { //和try catch直接包围区别就是: 抛出异常的地方不一样而已,这个在main线程中。而直接包围在FileInputStream中。 int c; InputStream in = new LowerCaseInputStream(new FileInputStream("src/t.txt")); // InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("src/t.txt"))); //用BufferedInputStream再包装一层利用缓冲机制 while((c = in.read()) >= 0){ //改善下性能,不写也没错只不过效率低点而已 System.out.print((char)c); } } } /* i love you, but, you are not a good girl */
打开看下FilterInputStream,发现是完全包装了下:InputStream,完全没有增加任何代码,但是继承它后告诉自己要重写这2个读取字节和字节数组的方法.其实里面直接包装下InputStream也是可以的。只不过有点别扭而已:
//转化为小写 class LowerCaseInputStream extends InputStream{ InputStream in; public LowerCaseInputStream(InputStream in) { this.in = in; } //针对字节 public int read() throws IOException{ int c = in.read(); return (c == -1 ? c : Character.toLowerCase(c)); } //针对字节数组 public int read(byte[] b, int offset, int len) throws IOException{ int result = in.read(b, offset, len); for(int i = offset; i < offset + result; i++){ b[i] = (byte)Character.toLowerCase((char)b[i]); } return result; } }了解了架构层面的东西,发现呃,原来是这样,不怕了。所以使用的时候最好知其然又知其所以然,这样才能理解到一定的深度,从而用的活灵活现,应对各种变化。
相关文章推荐
- Java 动态代理深入解析
- java多线程(二)锁对象
- java.lang.RuntimeException: HRegionServer Aborted
- java多线程(一)Race Condition现象及产生的原因
- Simple Java—Strings and Arrays(六)Java中的null值是什么?
- Java中的多线程总结
- java.lang.OutOfMemoryError
- Spring中SmartLifecycle的简单使用
- Simple Java—Strings and Arrays(五)如何在java中有效率的检查一个数组中是否有某值?
- 如何在Spring中配置Websocket
- Simple Java—Strings and Arrays(四)从length和length()开始谈Java
- Simple Java—Strings and Arrays(三)为什么String被设计成了不可变型
- 生产环境下JAVA进程高CPU占用故障排查
- Java基础:多态(重载和重写)
- java web eclipse中项目的加载过程
- eclipse 断点使用深入技能
- Struts2下载文件点击取消的异常处理
- Java解决Emoji表情符问题
- JAVA CAS原理深度分析
- Struts2配置精要之Result Types (Struts2.3.4)