Java IO中的装饰器模式—ecorator)和适配器模式(Adapter)
1.Java I/O库具有两个对称性,一种是字节流(byte),一种字符流(char).用一种字节(字符)流来构造另一种字节(字符)流用装饰器模式,而用字节流来构造字符流或用字符流构造字节流用适配器模式
其中:InputStream,outputStream及其子类为字节流,Reader,Writer及其子类为字符流.
如:
InputStreamReader类中InputStreamReader(InputStream?in)就是用字节流InputStream来构造字符流InputStreamReader这里用到了装饰器模式.
?
FilterOutputStream类中FilterOutputStream(OutputStream?out)就是用一种字节流来扩展另一种字节流,这里使用了适配器模式.(详细查看源代码)
?
定义一个ServletOutputStream将ServletOutputStream流字节转成ByteArrayOutputStream(对ServletOutputStream进行包装)
?private class WapperedServletOutputStream extends ServletOutputStream {
??private ByteArrayOutputStream bos = null;
??public WapperedOutputStream(ByteArrayOutputStream stream) throws IOException {
???bos = stream;
??}
??@Override
??public void write(int b) throws IOException {
???bos.write(b);
??}
?}
?
?
下面为获取jsp页面的内容关键代码:
代码使用了装饰器模式对HttpServletResponse 进行扩展getResponseData() 方法将response输出流转成byte[].
public class WapperedResponse extends HttpServletResponseWrapper {
?private ByteArrayOutputStream buffer = null;
?private ServletOutputStream out = null;
?private PrintWriter writer = null;
?public WapperedResponse(HttpServletResponse resp) throws IOException {
??super(resp);
??buffer = new ByteArrayOutputStream();
??out = new WapperedOutputStream(buffer);
??writer = new PrintWriter(new OutputStreamWriter(buffer, this.getCharacterEncoding()));
?}
?@Override
?public ServletOutputStream getOutputStream() throws IOException {
??return out;
?}
?@Override
?public PrintWriter getWriter() throws UnsupportedEncodingException {
??return writer;
?}
?@Override
?public void flushBuffer() throws IOException {
??if (out != null) {
???out.flush();
??}
??if (writer != null) {
???writer.flush();
??}
?}
?@Override
?public void reset() {
??buffer.reset();
?}
?public byte[] getResponseData() throws IOException {
??flushBuffer();
??return buffer.toByteArray();
?}
?private class WapperedOutputStream extends ServletOutputStream {
??private ByteArrayOutputStream bos = null;
??public WapperedOutputStream(ByteArrayOutputStream stream) throws IOException {
???bos = stream;
??}
??@Override
??public void write(int b) throws IOException {
???bos.write(b);
??}
?}
}