/*
* 当需要增强一个类的功能的时候,可以通过继承的方式来实现。这种方式代码结构清晰易于实现.
*
* 装饰者设计模式:
* 作用:增强一个类的功能,而且还可以让装饰类相互装饰.
* 思想:装饰者设计模式要让这些装饰类有一个共同的父类或者父接口,目的是为了让这些装饰类可以勾着给一个装饰链达到相互装饰的效果》
* 步骤:
* 1. 在装饰类的内部维护一个被维护类的引用;
* 2. 让装饰类有一个共同的父类或是父接口,让装饰类之间可以互相装饰;
*
*/
//带行号的缓冲输入字符流
package com.michael.lin;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class BufferedLineNum extends BufferedReader{
//1.在类的内部维护一个被装饰类的引用
BufferedReader bufferedReader;
int count = 1;
public BufferedLineNum(BufferedReader bufferedReader){
super(bufferedReader);
this.bufferedReader = bufferedReader;
}
//2.实现要增强的方法
public String readLine() throws IOException{
String line = bufferedReader.readLine();
if(line == null){
return null;
}
line = count + " " + line;
count++;
return line;
}
}
//带分号的输入字符流
class BufferedSem extends BufferedReader{
//1.维护一个被装饰类的引用;s
BufferedReader bufferedReader;
public BufferedSem(BufferedReader bufferedReader){
super(bufferedReader);
this.bufferedReader = bufferedReader;
}
//实现readLine方法
public String readLine() throws IOException{
String line = bufferedReader.readLine();
if(line==null){
return null;
}
line = line + ";";
return line;
}
}
//带双引号的输入缓冲字符流
class BufferedQuto extends BufferedReader{
//构建一个装饰类的引用
BufferedReader bufferedReader;
public BufferedQuto(BufferedReader bufferedReader){
super(bufferedReader);
this.bufferedReader = bufferedReader;
}
//实现readLine方法
public String readLine() throws IOException{
String line = bufferedReader.readLine();
if(line==null){
return null;
}
line = "\"" + line + "\"";
return line;
}
}
public class Demo7 {
public static void main(String[] args) throws IOException{
File file = new File("c:\\data.txt");
FileReader fileReader = new FileReader(file);
//建立缓冲输入字符流
BufferedReader bufferedReader = new BufferedReader(fileReader);
//带行号的输入缓冲字符流
String line = null;
BufferedLineNum bufferedLinenum = new BufferedLineNum(bufferedReader);
/*while((line=bufferedLinenum.readLine())!=null){
System.out.println(line);
}*/
//带分号的输入缓冲字符流
BufferedSem bufferedSem = new BufferedSem(bufferedLinenum);
/*while((line=bufferedSem.readLine())!=null){
System.out.println(line);
}*/
//带行号、分好、双引号的输入缓冲字符流
BufferedQuto bufferedQuto = new BufferedQuto(bufferedSem);
while((line=bufferedQuto.readLine())!=null){
System.out.println(line);
}
}
}