1 개요[ | ]
- template method pattern
- 템플릿 메소드 패턴
- 상속을 통해 기능을 확장하는 디자인 패턴
- 구체적인 것은 하위클래스에서 처리하도록 하는 구조
- 상속을 통해 슈퍼클래스의 기능을 확장할 때 사용하는 대표적인 방법
- 어떤 알고리즘에 대한 큰 틀이 결정된 상태에서 구체적인 설계를 서브클래스에 맡기는 디자인 패턴
- 상위클래스(템플릿)에 기본적인 로직의 흐름 구성, 그 일부를 추상 메소드·protected 메소드로 기술하여, 서브클래스에서 구현·오버라이딩하도록 하는 패턴
- 알고리즘의 뼈대를 정하고, 실제 동작을 정의하기 위해 클래스를 구현할 수 있게 해준다.
- 템플릿 메소드는 보통 추상 슈퍼클래스인 슈퍼클래스의 메소드이며, 여러 상위 단계의 관점에서 작업의 골격을 정의한다.
- 알고리즘의 구조를 식별하고, 실제 행동을 정의하는 클래스를 구현할 수 있다.
- 알고리즘의 구조를 변경하지 않고 알고리즘의 특정 단계들을 다시 정의할 수 있다.
- 의존성 역전 원칙(헐리우드 원칙)이 반영된 디자인 패턴이다.
2 관련 패턴[ | ]
- 전략 패턴은 일부분이 아니라 전체를 교체할 수 있도록 위임한다. 전략 패턴이 위임을 통해 알고리즘 전체를 변경할 수 있는 반면, 템플릿 메소드 패턴은 상속을 통해 알고리즘 일부만 변형시킬 수 있다.
- 팩토리 메소드 패턴은 템플릿 메소드 패턴의 특수한 경우이다.
3 예제[ | ]
Java
Copy
abstract class Game {
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* A template method : */
public final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
//Now we can extend this class in order
//to implement actual games:
class Monopoly extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Initialize players
// Initialize money
}
void makePlay(int player) {
// Process one turn of player
}
boolean endOfGame() {
// Return true if game is over
// according to Monopoly rules
}
void printWinner() {
// Display who won
}
/* Specific declarations for the Monopoly game. */
// ...
}
class Chess extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Initialize players
// Put the pieces on the board
}
void makePlay(int player) {
// Process a turn for the player
}
boolean endOfGame() {
// Return true if in Checkmate or
// Stalemate has been reached
}
void printWinner() {
// Display the winning player
}
/* Specific declarations for the chess game. */
// ...
}
4 같이 보기[ | ]
5 참고[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.