装饰模式是一种用于替代继承的技术,使用对象之间的关联关系取代类之间的继承关系。引入装饰类,扩充新功能。
继承也可以增加类的功能。但是使用继承,会使继承体系庞大,代码可能会冗余。
package com.Decorator;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
//带分号缓冲输入字符流--装饰类
class BufferedSemi extends BufferedReader{
BufferedReader reader = null;
public BufferedSemi(BufferedReader reader) {
super(reader);
this.reader = reader;
}
public String readLine()throws IOException{
String line = reader.readLine();
if(null == line)
return null;
line = line+";";
return line;
}
}
//带双引号缓冲输入字符流--装饰类
class BufferedQuot extends BufferedReader{
BufferedReader reader = null;
public BufferedQuot(BufferedReader reader) {
super(reader);
this.reader = reader;
}
public String readLine()throws IOException{
String line = reader.readLine();
if(null == line)
return null;
line = "\"" + line+ "\"";
return line;
}
}
//带行号缓冲输入字符流--装饰类
class BufferedLineNum extends BufferedReader{
int count = 1;
BufferedReader reader = null;
public BufferedLineNum(BufferedReader reader) {
super(reader);
this.reader = reader;
}
public String readLine()throws IOException{
String line = reader.readLine();
if(null == line)
return null;
line = count +":"+ line;
count++;
return line;
}
}
public class DecoratorDemo {
public static void main(String[] args) throws Exception{
File file = new File("E:\\testCode\\testWorkSpace\\chapter3\\src\\com\\Decorator\\DecoratorDemo.java");
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
BufferedSemi bs = new BufferedSemi(br);
// 将带分号的字符缓冲流传递给带有引号的缓冲流
// 将功能加强,这样每行数据既有了分号,又有了双引号
BufferedQuot bq = new BufferedQuot(bs);
// 将功能加强, 这样每行数据既有了分号,又有了双引号,又加上行号
BufferedLineNum bn = new BufferedLineNum(bq);
String line = null;
while(null != (line = bn.readLine())){
System.out.println(line);
}
}
}