裝飾者模式(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.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 stub
- int 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();
- }
- }
- }