标签:
装饰设计模式
1.装饰设计模式:
如:BufferedStream(InputStream in);
BufferedStream是基于InputStream的装饰类。
2、装饰和继承的区别:
/* * 自定义一个带行号的装饰类MyLineNumberReader */ package unit15; import java.io.*; class MyLineNumberReader extends MyBufferedReader{//装饰类 private Reader r; private int lineNumber; MyLineNumberReader(Reader r) {//根据多态思想,使用Reader作为参数对象类 super(r); } public String MyLineNumberReaderLine() throws IOException{ lineNumber++; return super.MyReadLine(); } public void setLineNumber(int lineNumber){ this.lineNumber = lineNumber; } public int getLineNumber(){ return lineNumber; } public void myClose() throws IOException{ r.close(); } } public class MyLineNumberTest { public static void main(String args[]){ try { FileReader fr = new FileReader("src/unit15/FileWriterTest.java"); MyLineNumberReader mlr = new MyLineNumberReader(fr); String str = null; while((str=mlr.MyLineNumberReaderLine())!=null){ System.out.println(str); } mlr.MyClose(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3、装饰设计模式的应用在IO输入/输出中最常见,其中有两个比较重要:
这种方式在键盘输入输出中非常适用:
示例:
1 package unit15; 2 3 import java.io.*; 4 5 public class TransfreamTest { 6 public static void main(String args[]){ 7 // InputStream in = System.in; 8 //InputStreamReader isr = new InputStreamReader(in); 9 // BufferedReader bfr = new BufferedReader(isr); 10 BufferedReadser buf = new BufferedReader(new InputSream(System.in));//键盘输入组合格式 11 // OutputStream out = System.out; 12 // OutputStreamWriter osw = new OutputStreamWriter(out); 13 // BufferedWriter brw = new BufferedWriter(osw); 14 BufferedWriter bfw = new BufferedWriter(new OutputSteam(System.out));//输出到控制台 15 16 String str = null; 17 try { 18 while((str=bfr.readLine())!= null){ 19 if("over".equals(str)) 20 break; 21 //System.out.println(str); 22 brw.write(str); 23 brw.newLine(); 24 brw.flush(); 25 26 } 27 bfr.close(); 28 brw.close(); 29 } catch (IOException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 34 } 35 36 }
标签:
原文地址:http://www.cnblogs.com/chizhongyue/p/4608235.html