/*
自定義讀取緩衝區
裝飾設計模式:
當需要對對象進行功能增強的時候,可以定義類,將原有對象傳入,基於原有功能,擴展功能
*/
package myBufferedReader;
import java.io.*;
class MyBufferedReader
{
public static void main(String[] args) throws IOException
{
//人吃飯舉例
Person p=new Person();
SuperPerson sp=new SuperPerson(p);
sp.superEat();
//自定義讀取緩衝區
FileReader r=new FileReader("BufferedCopyDemo.java");
MyReadLine mrl=new MyReadLine(r);
System.out.println(mrl.readLine());
}
}
//自定義緩衝區
class MyReadLine
{
private FileReader r;
MyReadLine(FileReader r)
{
this.r=r;
}
//讀一行
public String readLine() throws IOException
{
StringBuilder sb=new StringBuilder();
int ch=0;
while((ch=r.read())!=-1)
{
if(ch=='\r')
continue;
if(ch=='\n')
return sb.toString();
sb.append((char)ch);
}
if(sb.length()!=0)
return sb.toString();
return null;
}
//關閉
public void myClose() throws IOException
{
r.close();
}
}
//人類
class Person
{
public void eat()
{
System.out.println("吃飯");
}
}
//高級人類
class SuperPerson
{
Person p;
SuperPerson(Person p)
{
this.p=p;
}
public void superEat()
{
System.out.println("開胃酒");
System.out.println("吃飯");
System.out.println("飯後果");
}
}
裝飾設計模式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.