您的位置:首页 > 编程语言 > Java开发

装饰者模式--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;
}
}
了解了架构层面的东西,发现呃,原来是这样,不怕了。所以使用的时候最好知其然又知其所以然,这样才能理解到一定的深度,从而用的活灵活现,应对各种变化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: