본문 바로가기

Design Patterns/영문 위키(Wikipedia)

Template method pattern

먼저 이 글은 영문 위키의 글을 번역한 글임을 알려드립니다.

영어실력이 부족한 관계로 오역이 있을 수도 있습니다.

원문주소 : http://en.wikipedia.org/wiki/Template_method_pattern



Behavioral - Template method pattern

소프트웨어 공학(software engineering)에서 template method pattern디자인 패턴(design pattern) 중 하나이다. 행위적 패턴(behavioral pattern) 중 하나이고, C++ templates와는 무관하다.

도입 Introduction

template method 는 특정 알고리즘프로그램 스켈레톤(program skeleton)을 정의한다. 하나 이상의 알고리즘 단계들이 하위 클래스(서브 클래스)에서 재구현(overriden)될 수 있는데, 이 때 중요한 뼈대가 되는 알고리즘은 그대로 유지한체 다른 동작을 할수 있도록 한다.


객체 지향 프로그래밍에서 한 클래스는 특정 알고리즘 설계(algorithm design)의 기본적인 단계들을 제공하도록 만들어진다. 이러한 단계들은 추상메서드(abstract methods)를 사용해서 구현된다. 서브클래스에서는 추상 메서드를 실제로 동작하게 끔 구현한다. 뼈대에 해당하는 알고리즘은 유지한채로 서브 클래스에서 각 단계들의 구현만 달라지게 된다.


template method 패턴은 의미(semactics)에 해당하는 큰 그림과 세부 구현, 그리고 일련의 메서드들을 다룬다. 이런 큰 그림이 추상 메서드와 비추상(non-abstract) 메서드를 호출한다. 비추상 메서드는 template method에 의해 전적으로 처리되지만, 서브 클래스에서 구현되는 추상 메서드는 이 패턴의 힘과 자유도를 제공한다. 추상 메서드의 일부 또는 전체는 서브 클래스에서 구현이 되는데, 서브 클래스를 작성하는 사람이 더 큰 의미론적으로는 변화를 최소화시킨 채 특정 행동을 할 수 있도록 해준다. 


template method 패턴은 자주 사용된다. 한 메서드가 오직 하나의 추상 메서드를 호출하는 경우는 정말 최소한으로 template method를 사용한 케이스라 볼 수 있다. 어떤 개발자가 다형성(polymorphic)을 전적으로 사용하고 있다면, 이 디자인 패턴은 꽤나 자연스러운 결과이다. template method는 지금 당장 존재하는 값을 소프트웨어에 추가하기 위해 사용되거나 미래에 더 강화된 기능을 위해 사용된다. 


template method 패턴은 Non-Virtual Interface(NVI) 패턴과 밀접한 관련이 있다. NVI 패턴은 비추상 메서드가 추상 메서드를 호출하는 것의 장점을 잘 알고 있다. NVI 패턴은 아주 작은 소프트웨어 생산과 런타임 비용을 들게 할 수 있다. 많은 상업적 소프트웨어 프레임웍(software frameworks)에서는 NVI 패턴을 채용하고 있다.


Template method 패턴은 Adapter Pattern에서 하듯이 GRASP를 구현한다. 다른 점은 Adapter는 여러 오퍼레이션에게 같은 인터페이스를 제공하지만, Template Method는 오직 하나에게만 제공한다는 점이다.

구조 Structure



사용법 Usage

Template method는 다음과 같은 경우에 사용된다.

  • 변할 수 있는 행위에 대한 구현은 서브 클래스에서 메서드 오버라이딩(method overriding)을 통해 하도록 한다.
  • 코드의 중복 제거 : 추상 클래스의 알고리즘에서 일반적인 흐름 구조는 한번만 구현되고, 필요한 변화는 각 서브클래스에서 구현된다.
  • 어떤 지점에서 서브 클래싱(subclassing)이 가능한지를 조절할 수 있다. 흐름에 대해 근본적인 부분부터 다 바꿔버리는 단순한 다형성 오버라이드와는 반대로, 흐름의 일부에 대해서만 변화를 허용한다.


template 패턴을 사용한 애플리케이션의 결과인 조절 구조(inversion of control)헐리웃 원리(Hollywood Principle, "날 부르지마, 내가 널 부를테니..") 같다고 언급된다. 이 원리를 이용하면 부모 클래스에 있는 template method는 서브클래스의 메서드를 필요할 때 호출함으로써 전반적인 프로세스를 관리한다.  다음의 자바 예를 보면 알 수 있다. 


예 Example

/**
 * An abstract class that is 
 * common to several games in
 * which players play against 
 * the others, but only one is
 * playing at a given time.
 */
 
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. */
 
    // ...
}


'Design Patterns > 영문 위키(Wikipedia)' 카테고리의 다른 글

Strategy pattern  (0) 2012.07.04
State pattern  (0) 2012.07.03
Observer pattern  (0) 2012.06.27
Memento pattern  (0) 2012.06.20
Mediator pattern  (0) 2012.06.19