jdk中的Decorate Pattern - java.io

本文介绍了Java I/O包中的装饰模式设计,通过FilterInputStream作为装饰器为输入流提供缓存和流行数支持,并展示了如何实现自定义装饰器。文章通过实例演示了BufferedInputStream、LineNumberInputStream和MyInputStream类的应用。

java.io是使用Decorate Pattern设计的:

其中FilterInputStream为Decorate Pattern中的Decorator,注意FilterInputStream即不是接口也不是抽象类,是一个实实在在的类,形如:

public class FilterInputStreamextends InputStream{
	protected  InputStream in;
	
	protected  FilterInputStream(InputStream in){
		this.in = in;
	}  	
	...
}

它的子类提供了很多“装饰”功能,如:

BufferedInputStream类会为输入流提供缓存区,LineNumberInputStream类提供对输入流行号的支持等等

一个提供输入缓存、并且能够获取输入文件流行数的小程序:

public class Test {
	public static void main(String[] args) {
		try {
			InputStream in = new FileInputStream(new File("e:\\test.txt"));
			BufferedInputStream in1 = new BufferedInputStream(in);
			LineNumberInputStream in2 = new LineNumberInputStream(in1);
			System.out.println(in2.getLineNumber());	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

 当然也可以实现自己的“装饰器”:

public class MyInputStream extends FilterInputStream {
	protected MyInputStream(InputStream in) {
		super(in);
	}

	public int read(byte[] b) throws IOException {
		System.out.println(b+" ");
		return super.read(b);
	}
	
	public static void main(String[] args){
		try {
			InputStream in = new FileInputStream(new File("e:\\test.txt"));
			BufferedInputStream in2 = new BufferedInputStream(in);
			MyInputStream in3 = new MyInputStream(in2);
			
			byte[] bs = {(byte)1,(byte)2};
			in3.read(bs);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
[B@35ce36 

jdk中还有很多类是使用Decorate Pattern设计的,如java.io.Reader、java.io.Writer和java.io.OutputStream等

例如:java.io.Reader:

 

并且FilterReader是一个抽象类,可以很方便的自己扩展需要的“装饰者”

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/sean-zou/archive/2013/05/29/3710053.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值