DRY原则和设计模式

前两天在做统计程序时,需要读取linux中的日志文件,在网上查了下,就有了结论,于是,根据需要,我写下了这样的代码:

public class dealFile {
	public static void dealContent(String[] commands){
		BufferedReader reader=null;
		try{
			Process process = Runtime.getRuntime().exec (commands);
			reader = new BufferedReader (new InputStreamReader(process.getInputStream()));			           
			String line;			           
			while ((line = reader.readLine ()) != null){
			  //处理的代码
                           System.out.println(line);			  
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		  if(reader!=null){			  
			  try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  }
		}
	}
}

可是问题来了,我还需要执行其他的命令,做出不同的处理,也就是,我的处理也需要参数化,该怎么办呢,经过一番思索,进行了这样的处理:

public class ReadLinuxFileHelper {
	public static void dealContent(String[] commands,DealLinuxFile handler){
		BufferedReader reader=null;
		try{
			Process process = Runtime.getRuntime().exec (commands);
			reader = new BufferedReader (new InputStreamReader(process.getInputStream()));			           
			String line;			           
			while ((line = reader.readLine ()) != null){
			   handler.readLine(line);	        
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		  if(reader!=null){			  
			  try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  }
		}
	}
}


DealLinuxFile.java代码:

public interface DealLinuxFile {
	/**
	 * 读入数据行
	 * @param line
	 */
	 void readLine(String line);
	
}

调用的时候:

//job的运行过程报告
	private void programProcedure(){		
		String[] beginCommands={"/bin/bash", "-c","grep '开始' "+logFile};
		String[] endCommands={"/bin/bash", "-c","grep '结束' "+logFile};
		final StringBuilder logContent=new StringBuilder();
		ReadLinuxFileHelper.dealContent(beginCommands, new DealLinuxFile() {			
			@Override
			public void readLine(String line) {
				logContent.append(line);				
			}			
		});
		ReadLinuxFileHelper.dealContent(endCommands, new DealLinuxFile() {			
			@Override
			public void readLine(String line) {
				logContent.append(line);
			}			
		});
		dealLogContent(logContent);
	}


用这种方式,实现了处理过程的参数化。

写完之后,感觉这种方式好像有点奇怪,之前没有用这种方式写过程序,想了想,这好像是一个什么模式,在网上搜了下,有一篇文章讲的挺好:http://blog.sina.com.cn/s/blog_6c26b0260100nyba.html,

原来这就是模板模式或者说是策略模式。

想了想自己思考的过程,起初自己只是想重用代码,然后很自然的就派生出一个接口,然后发现这居然就是一个设计模式,之所以会有这种结果,我想是两方面造成的:

1、厚积薄发,经过几年的开发,自然就有了这种功力。

2、之前读的关于设计模式的记忆被启发了。

其实这应该是DRY(Don't repeat yousellf)思想的运用,设计模式在这里是对该原则的实现。

不清楚理论,刚开始用的时候还有点误打误撞,但是我仔细的了解了模板和策略模式的理论后,对整个的过程就很清楚了,理论也就是这样指导实践的,实践反过来加深了对理论的理解。

你可能感兴趣的:(java,设计模式,string,exception,null,interface)