Stoker的Java學習之裝飾者模式
阿新 • • 發佈:2018-12-10
Java學習之裝飾者模式
一.裝飾者模式(解耦 不讓類和類產生繼承的關係)
對 物件原有的功能進行升級
書寫步驟: 1.明確被裝飾的物件 2.將被裝飾的物件 通過構造方法傳入 裝飾類 裝飾類中 肯定有 一個成員變數 就是 被裝飾的物件 3.擁有被裝飾的物件 相當於可以呼叫該物件的所有方法 就可以對該方法進行升級。
public class Demo01 { public static void main(String[] args) { Student student = new Student(); LoStudent loStudent = new LoStudent(student); loStudent.study(); } } // 學習的介面 interface Study{ void study(); } // 在校學生 class Student implements Study{ @Override public void study() { System.out.println("在校學習了 C C++ C#"); } } //裝飾類 class LoStudent implements Study{ //將被裝飾者宣告為成員變數 private Student student; //提供有參的構造方法 public LoStudent(Student student) { super(); this.student = student; } public LoStudent() { super(); } // 對方法進行裝飾(升級) @Override public void study() { // 呼叫原有方法 student.study(); //裝飾新功能 System.out.println("學習Java H5 U3D"); } }
二.列印流
-
1.永遠不會拋IO異常
-
2.原樣輸出到目的端
-
PrintStream 構造方法: 字串路徑 檔案物件 位元組流物件
-
PrintWriter 構造方法: 字串路徑 檔案物件 位元組流物件 字元流物件
-
注意: 只有操作流物件 才能自動重新整理
-
System in BufferedInputStream
-
System out PrintStream
從控制檯輸入文字 寫到檔案中(可以寫中文)
public class Demo04 { public static void main(String[] args) throws IOException { System.out.println("請輸入:"); InputStream in = System.in; // 使用轉換流 將位元組轉字元 InputStreamReader isr = new InputStreamReader(in); // 讀一行 BufferedReader readline() BufferedReader br = new BufferedReader(isr); // 列印流原樣輸出 一次寫一行檔案 File file = new File("/Users/lanou/Desktop/Test/talang.txt"); FileWriter fw = new FileWriter(file); PrintWriter pw = new PrintWriter(fw, true); int num = 0; //讀寫 String string = ""; while ((string = br.readLine()) != null) { num++; // 結束條件 if (string.equals("quit")) { break; } // 寫入檔案 pw.println(num + ":" + string); } // 關閉資源 br.close(); pw.close(); } }
三.合併流(位元組流 任何檔案都能合併)
SequenceInputStream(Enumeration<? extends InputStream> e)
作用:可以將多個檔案合併成一個新的檔案。 合併三個檔案 SequenceInputStream(Enumeration<? extends InputStream> e) 將要合併的檔案三個流 新增到vector
File f1 = new File("/Users/lanou/Desktop/Test/1.txt"); File f2 = new File("/Users/lanou/Desktop/Test/2.txt"); File f3 = new File("/Users/lanou/Desktop/Test/3.txt"); // 建立位元組流 並將三個流新增到集合 Vector<FileInputStream> vector = new Vector<>(); vector.add(new FileInputStream(f1)); vector.add(new FileInputStream(f2)); vector.add(new FileInputStream(f3)); // 獲取迭代器(列舉器) Enumeration<FileInputStream> elements = vector.elements(); // 合併檔案 SequenceInputStream sis = new SequenceInputStream(elements); InputStreamReader isr = new InputStreamReader(sis); BufferedReader br = new BufferedReader(isr); File file = new File("/Users/lanou/Desktop/Test/5.txt"); FileWriter fw = new FileWriter(file); PrintWriter pw = new PrintWriter(fw, true); String string = null; while ((string = br.readLine()) != null) { // 寫 pw.println(string); } br.close(); pw.close(); }