3단계에서 보면 calc()랑 multiply()부분에서

while문에서 가져오는 부분이 중복된다는 걸 볼수 있다.

이걸 템플릿/콜백 패턴으로 중복 제거하면(어디까지 갈것인가..두둥..==ㅣ)

public class Calculator {
public Integer lineReadTempleter(String filepath,LineCallback callback,int initVal) throws IOException{
BufferedReader br = null;
try {
   br = new BufferedReader(new FileReader(filepath));
   String line = null;
   Integer res = initVal;
   
   while( (line = br.readLine()) != null ){
    res = callback.doSomethingWithLine(line, res);
   }
   return res;
} catch (IOException ie) {
// TODO: handle exception
ie.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
if(br!=null){
try {
br.close();
} catch (Exception e2) {
// TODO: 무시
}
}
}
return 0;
}
public Integer calcSum(String filepath) throws IOException{
LineCallback callback = 
new LineCallback(){
@Override
public Integer doSomethingWithLine(String line, Integer value) {
// TODO Auto-generated method stub
return Integer.parseInt(line) + value;
}
};
return this.lineReadTempleter(filepath, callback, 0);
}

public int calcMultiply(String filepath) throws IOException{
//TODO Auto-generated method stub
LineCallback callback = 
new LineCallback(){
@Override
public Integer doSomethingWithLine(String line, Integer value) {
// TODO Auto-generated method stub
return Integer.parseInt(line) * value;
}
};
return this.lineReadTempleter(filepath, callback, 1);
}
}

이때 콜백으로 처리된 인터페이스는 다음과 같다.

public interface LineCallback {
Integer doSomethingWithLine(String line,Integer value);
}

흠냐...대단하단 말밖에 안나온다...^^;

계속해서 리팩토링 되는 것 같다...(소름끼침..==ㅣ);

+ Recent posts