一個很不錯的抽象類的實現

  1.  
  1. <?php 
  2. /* 
  3.  * Created on 2011-5-16 
  4.  * 
  5.  * To change the template for this generated file go to 
  6.  * Window - Preferences - PHPeclipse - PHP - Code Templates 
  7.  */ 
  8. abstract class car{ 
  9.  
  10.     abstract function getMaxSpeed(); 
  11.  
  12. class FastCar extends car{ 
  13.  
  14.     function getMaxSpeed() 
  15.     { 
  16.         return 500; 
  17.     } 
  18.  
  19.  
  20.  
  21.  
  22. class SlowCar extends car{ 
  23.  
  24.     function getMaxSpeed() 
  25.     { 
  26.         return 50; 
  27.     } 
  28.  
  29.  
  30.  
  31.  
  32. class Street{ 
  33.  
  34.     protected $speedLimit
  35.     protected $cars
  36.     public function __construct($speedLimit=200) 
  37.     { 
  38.         $this->cars=array(); 
  39.         $this->speedLimit=$speedLimit
  40.     } 
  41.  
  42.     protected function islegal($car
  43.     { 
  44.         if($car->getMaxSpeed() < $this->speedLimit) 
  45.             return true; 
  46.         else 
  47.             return false; 
  48.  
  49.     } 
  50.  
  51.     public function addcars($car
  52.     { 
  53.         if($this->islegal($car)) 
  54.         { 
  55.             echo "this car is allowed to run in the street"
  56.             $this->cars[]=$car
  57.         }else
  58.             echo "it's fobidden to run"
  59.  
  60.         } 
  61.  
  62.  
  63.     } 
  64.  
  65.  
  66.     public function getcarslist() 
  67.     { 
  68.         print_r($this->cars); 
  69.     } 
  70.  
  71.  
  72. $b=new street(); 
  73. $b->addcars(new FastCar); 
  74. echo "<br>"
  75. $b->addcars(new SlowCar); 
  76. $b->addcars(new SlowCar); 
  77. $b->addcars(new SlowCar); 
  78. $b->addcars(new SlowCar); 
  79. $b->addcars(new SlowCar); 
  80.  
  81. $b->getcarslist(); 
  82. ?> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章