[关键字]:java,design pattern,设计模式,《Java与模式》学习,decorator,装饰模式,Unix
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com)
[正文]:
package pattern.decorator.grep;
import java.io.*;
/**
* 装饰模式(Decorator Pattern):Grep
*
* Grep是UNIX中的命令,
* 使用命令"grep BMW file",
* 就可以在file中找出含有BMW的行,并显示。
*
* @version 2009-6-6
* @author Winty(wintys@gmail.com)
*/
public class Grep{
public static void main(String[] args)throws Exception{
GrepView view = new GrepView();
if(args.length < 2){
view.println("Usage: java Grep targetString fileName");
view.println("e.g.:java Grep BMW C:/sample.txt");
System.exit(0);
}
GrepReader grep;
FileReader file = new FileReader(args[1]);
grep = new GrepReader(file , args[0] , view);
grep.search();
}
}
class GrepReader extends FilterReader{
private LineNumberReader reader;
private String target;
private GrepView view;
/**
*@param in 在输入流in中查找目标字符串
*@param target 要查找的目标字符串
*@param view 查找结果输出
*/
public GrepReader(Reader in , String target , GrepView view){
super(in);
reader = new LineNumberReader(in);
this.target = target;
this.view = view;
}
public void search()throws Exception{
String line = null;
while((line = reader.readLine())!=null){
int index = -1;
if((index = line.indexOf(target)) != -1){
String str;
str = "line" + reader.getLineNumber() + " column" + (index +1) +":" + line;
view.println(str);
}
}
reader.close();
}
}
class GrepView{
private PrintStream out;
public GrepView(){
this.out = System.out;
}
public void println(String str){
out.println(str);
}
}
posted on 2009-06-07 22:42
天堂露珠 阅读(991)
评论(2) 编辑 收藏 所属分类:
Pattern