본문 바로가기

아는 만큼 보인다/Design Pattern

템플릿/콜백 패턴 (익명 내부 클래스를 주입하는 전략패턴)

템플릿/콜백 패턴은 전략패턴이다.

client가 특정 인터페이스를 구현한 클래스를 생성하여 변하지 않는 클래스에 주입시에..

익명 내부 클래스를 생성/주입하는 조금 특별한 경우라면.. 

(스프링에서) 이를 그냥 전략패턴이라고 부르기 보다는 조금 구분짓기 위해 템플릿/콜백 패턴이라 부른다.



템플릿/콜백 패턴에는 몇 가지 특징이 있다.

1. 인터페이스는 단 하나의 메소드를 선언하고 있다. 

   (익명클래스 생성시에 override해서 구현할 메소드는 단 하나다)

2. 익명클래스내의 구현메소드가 client(외부 클래스)의 final 변수를 참조할 수 있다.



사용예) 

public class TestClient {

....

@Test
public void testSum() {
    int sum = calculator.sum(filePath);
    assertThat(sum, is(7));
}

@Test
public void testMultiply() {
    int mul = calculator.mul(filePath);
    assertThat(mul, is(12));
}

}


public class Calculator{

public int sum(String filePath) {

CallBackInterface sumCallBack = new CallBackInterface () {

@override
public int  doSomethingWithLineValue(String lineValue, int prevResult) {
    return prevResult + Integer.valueOf(lineValue);

}

}

return readLineTemplate(filePath, sumCallBack, 0);

}


public int mul(String filePath) {

CallBackInterface sumCallBack = new CallBackInterface () {

@override
public int  doSomethingWithLineValue(String lineValue, int prevResult) {
    return prevResult * Integer.valueOf(lineValue);

}

}

return readLineTemplate(filePath, mulCallBack, 1);

}


public readLintTemplate(String filePath, CallBackInterface callBack, int initVal) {

BufferedReader br = null;

try {

BufferedReader br = new BufferedReader(new FileReader(filePath));
Integer res = initVal;
String line = null;
while((line = br.readLine()) != null) {
    res = callBack.doSomethingWithLineValue( line, res );

}
return res;

} catch (IOException e) {

e.printStackTrace();

throw e;

} finally {

if(br!=null) try { br.close(); } catch (IOException e) { e.printStackTrace(); }

}

}

}


public interface  CallBackInterface {
    public int  doSomethingWithLineValue(String lineValue, int prevResult) ;

}


출처 : 토비의 스프링 3 (이일민 저)