php模板模式(template design)

没有写停止条件,所以会一直运行哟。

php
/*
The template design pattern defines the program skeleton of an algorithm in a
method. It lets us, via use of class overriding, redefine certain steps of an algorithm
without really changing the algorithm's structure.
*/

abstract class Game {
    private $playerCount;
    
    abstract function initializeGame();
    abstract function makePlay($player);
    abstract function endOfGame();
    abstract function printWinner();
    
    public function playOneGame($playerCount) {
        $this->playerCount = $playerCount;
        $this->initializeGame();
        $j = 0;
        while (!$this->endOfGame()) {
            $this->makePlay($j);
            $j = ($j + 1) % $playerCount;
        }
        $this->printWinner();
    }
}

class Monopoly extends Game {
    public function initializeGame() {
        echo 'Monopoly_initializeGame.
'; } public function makePlay($player) { echo 'Monopoly_makePlay.
'; } public function endOfGame(){ echo 'Monopoly_endOfGame.
'; } public function printWinner(){ echo 'Monopoly_printWinner.
'; } } class Chess extends Game { public function initializeGame() { echo 'Chess_initializeGame.
'; } public function makePlay($player) { echo 'Chess_makePlay.
'; } public function endOfGame(){ echo 'Chess_endOfGame.
'; } public function printWinner(){ echo 'Chess_printWinner.
'; } } $game = new Chess(); $game->playOneGame(2); $game = new Monopoly(); $game->playOneGame(4); ?>

 

转载于:https://www.cnblogs.com/aguncn/p/11185957.html

你可能感兴趣的:(php)