ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 행위패턴 : Template Method 패턴
    디자인패턴 2013. 3. 25. 09:00
    반응형

    분류 : 행위패턴(Behavioral Patterns)


    정의 :

    메소드에서 알고리즘의 뼈대를 정의하는 패턴. C++의 Template하고는 상관 없음.

    용도 :

    코드에서의 중복을 피하기 위해서임. 공통적인 작업흐름은 추상클래스쪽에 한번 정의하고, 나머지 다양한 구현들은 각각의 서브클래스들에서 담당함.




    소스

    
    /**
     * 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();
        }
    }
    
    
    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
        	return true;
        }
        void printWinner() {
            // Display the winning player
        }
        /** Specific declarations for the chess game. */
     
        // ...
    }
    
    
    //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
    	  return true;
      }
      void printWinner() {
          // Display who won
      }
      /** Specific declarations for the Monopoly game. */
    
      // ...
    }
    



    참고자료

    http://en.wikipedia.org/wiki/Template_method_pattern

    반응형

    '디자인패턴' 카테고리의 다른 글

    Reactor 패턴  (1) 2014.09.03
    행위패턴 : Visitor 패턴  (0) 2013.03.27
    행위패턴 : Strategy 패턴  (0) 2013.03.18
    행위패턴 : State 패턴  (0) 2013.03.11
    행위패턴 : Observer 패턴  (0) 2013.03.04

    댓글

Designed by Tistory.