템플릿/콜백 패턴은 전략패턴이다.
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 (이일민 저)
'아는 만큼 보인다 > Design Pattern' 카테고리의 다른 글
Builder Pattern (0) | 2014.12.10 |
---|---|
Service Provider Framework Pattern (0) | 2014.12.03 |
데코레이터 패턴과 프록시 패턴 (0) | 2012.06.11 |
전략 패턴 (using Interface) (0) | 2012.05.18 |
템플릿 메소드 패턴 (abstract, extends) (0) | 2012.05.18 |