曾梦垚

导航

装饰器模式

class BufferedReadLineNum1 extends BufferedReader{
//内部维护的被装饰者类
BufferedReader bufferedReader;
int count = 1;
public BufferedReadLineNum1(BufferedReader read){
super(read);
this.bufferedReader = read;
}
//开始拓展功能
public String readLine()throws IOException{
String content = bufferedReader.readLine();
if(content == null){
return null;
}
content = count + " " +content;
count++;
return content;
}
}

//带分号
class BufferedReadLineSemi1 extends BufferedReader{
BufferedReader bufferedReader;
public BufferedReadLineSemi1(BufferedReader read){
super(read);
this.bufferedReader = read;
}
//开始拓展功能
public String readLine()throws IOException{
String content = bufferedReader.readLine();
if(content == null){
return null;
}
return content+";";
}
}
//带引号
class BufferReaderLineMark1 extends BufferedReader{
//1.内部需要一个被装饰类的应用
BufferedReader bufferedReader;
public BufferReaderLineMark1(BufferedReader read){
super(read);
this.bufferedReader = read;
}
//重写
public String readLine()throws IOException{
String content = bufferedReader.readLine();
if(content == null){
return null;
}
return "\""+content+"\"";
}
}
public class Demo2 {


public static void main(String[] args) throws IOException {

//1.开启通道
FileReader reader = new FileReader("C:\\zmy\\test.txt");
//2.创建缓冲流
BufferedReader bufferedReader = new BufferedReader(reader);

//3.创建带引号
BufferReaderLineMark1 lineMark1 = new BufferReaderLineMark1(bufferedReader);

//3.创建带行号
BufferedReadLineNum1 lineNum1 = new BufferedReadLineNum1(lineMark1);

//3.创建带分号
BufferedReadLineSemi1 lineSemi1 = new BufferedReadLineSemi1(lineNum1);

//3.创建带引号
//BufferReaderLineMark1 lineMark1 = new BufferReaderLineMark1(lineSemi1);

//4.读取数据
String content = null;
while((content = lineSemi1.readLine()) != null){
System.out.println(content);
}

//关闭
lineSemi1.close();
}

}

posted on 2016-12-09 19:20  曾梦垚  阅读(89)  评论(0编辑  收藏  举报