템플릿 메소드 패턴

Jmnote (토론 | 기여)님의 2022년 3월 31일 (목) 09:15 판

1 개요

template method pattern
템플릿 메소드 패턴
  • 상속을 통해 기능을 확장하는 패턴
  • 구체적인 것은 하위클래스에서 처리하도록 하는 구조
  • 상속을 통해 슈퍼클래스의 기능을 확장할 때 사용하는 대표적인 방법
  • 어떤 알고리즘에 대한 큰 틀이 결정된 상태에서 구체적인 설계를 서브클래스에 맡기는 디자인 패턴
  • 상위클래스(템플릿)에 기본적인 로직의 흐름 구성, 그 일부를 추상 메소드·protected 메소드로 기술하여, 서브클래스에서 구현·오버라이딩하도록 하는 패턴
  • 스프링 프레임워크 등 프레임워크에서 자주 사용되는 구조

 

2 예제

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. */
 
    // ...
}

3 같이 보기

4 참고

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}