Интернет магазин китайских планшетных компьютеров



Компьютеры - Шаблонный метод (шаблон проектирования) - Пример кода

30 марта 2011


Оглавление:
1. Шаблонный метод (шаблон проектирования)
2. Пример кода



В примере шаблонный метод реализуется для игр, в которых игроки по очереди делают свой ход.

/**
 * 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;
 
    abstract boolean endOfGame;
 
    abstract void printWinner;
 
    /* A template method : */
    final void playOneGame {
        this.playersCount = playersCount;
        initializeGame;
        int j = 0;
        while ) {
            makePlay;
            j =  % 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 money
    }
 
    void makePlay {
        // Process one turn of player
    }
 
    boolean endOfGame {
        // Return true of 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 {
        // Put the pieces on the board
    }
 
    void makePlay {
        // 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. */
 
    // ...
 
}


Просмотров: 1622


<<< Шаблон функционального дизайна
Шаблоны J2EE >>>