1 <?php 2 3 /** 4 * 模板方法模式又叫模板模式,该模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。 5 * 模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。 6 * 7 * 由于模板定义了子类的行为,所以是行为型模式 8 */ 9 10 abstract class Game 11 { 12 abstract public function initialize(); 13 abstract public function start(); 14 abstract public function end(); 15 16 17 final public function play() 18 { 19 $this->initialize(); 20 $this->start(); 21 $this->end(); 22 } 23 } 24 25 26 class BasketBall extends Game 27 { 28 public function initialize() 29 { 30 echo "<br/>BasketBall initialize"; 31 } 32 33 public function start() 34 { 35 echo "<br/>BasketBall start"; 36 } 37 38 public function end() 39 { 40 echo "<br/>BasketBall end"; 41 } 42 } 43 44 class FootBall extends Game 45 { 46 public function initialize() 47 { 48 echo "<br/>FootBall initialize"; 49 } 50 51 public function start() 52 { 53 echo "<br/>FootBall start"; 54 } 55 56 public function end() 57 { 58 echo "<br/>FootBall end"; 59 } 60 } 61 62 63 $b = new BasketBall(); 64 $b->play(); 65 66 $f = new FootBall(); 67 $f->play();