마지막소스 첨부는

자 이제 마지막 리팩토링이네영..

책에선 제네릭을 이용한 다양한 형태로의 변환이 되는 자유로운 팩토링을 보였는데 정말 새롭고 유용한 방법인것 같아서 강추!!

암튼 소스는 다음과 같습니다..

만약 String값을 이용해서 덧붙이는 기능을 사용하고자 할때에는 이런식으로 바꿔주면 되는군요.

우선 Test해볼 메소드입니다.(여기서 파일안에 있는 숫자를 순서대로 덧붙이는 메소드입니다)

@Test public void concatenateOfNumber() throws IOException{
String concateStr = calculator.concatenateString(filepath);
assertThat(concateStr,is("1243"));
}

public class Calculator {
public <T> T lineReadTempleter(String filepath,LineCallback<T> callback,T initVal) throws IOException{
BufferedReader br = null;
try {
   br = new BufferedReader(new FileReader(filepath));
   String line = null;
   T 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 null;
}
public Integer calcSum(String filepath) throws IOException{
LineCallback<Integer> callback = 
new LineCallback<Integer>(){
@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<Integer> callback = 
new LineCallback<Integer>(){
@Override
public Integer doSomethingWithLine(String line, Integer value) {
// TODO Auto-generated method stub
return Integer.parseInt(line) * value;
}
};
return this.lineReadTempleter(filepath, callback, 1);
}
//주어진 String을 합치는 메소드
public String concatenateString(String filepath) throws IOException{
LineCallback<String> callback = 
new LineCallback<String>(){
@Override
public String doSomethingWithLine(String line, String value) {
// TODO Auto-generated method stub
return value + line;
}
};
return this.lineReadTempleter(filepath, callback, "");
}
}

여기서 주의해서 봐야할껀 템플릿 메소드에 T라고 제네릭코드 가 들어간다는 점..

암튼 참 도움 많이 되는 책인것 같습니다..

토비의 스프링 화이팅!!

+ Recent posts