1.版本一
<?php /** * Created by Victor * User: Victor * Date: 2018/3/16 * Time: 9:54 */ abstract class Lesson { protected $duration; const FIXED = 1; const TIMED = 2; private $_costtype; function __construct($duration, $costtype = 1) { $this->_costtype = $costtype; $this->duration = $duration; } public function cost() { switch ($this->_costtype) { case self::FIXED: return 5 * $this->duration; break; case self::TIMED: return 30; break; default : $this->costtype = self::TIMED; return 30; } } public function chargeType() { switch ($this->_costtype) { case self::FIXED: return 'Fixed rate'; break; case self::TIMED: return 'Hour rate'; break; default : $this->costtype = self::TIMED; return 'Hour rate'; } } } class Lecture extends Lesson { } class Seminar extends Lesson { } abstract class CostStrategy { } $lectur = new Lecture(50, Lesson::FIXED); $sminar = new Seminar(50, Lesson::TIMED); print_r($lectur->cost() . $lectur->chargeType());//输出 print_r($sminar->cost() . $lectur->chargeType());//输出
2.版本二:通过组合模式替代原来的继承,完成的类的功能改的阔扩展。
<?php /** * Created by Victor * User: Victor * Date: 2018/3/16 * Time: 9:54 */ abstract class Lesson { private $_duration; private $_costStrategy; function __construct($duration, CostStrategy $costStrategy) { $this->_costStrategy = $costStrategy; $this->_duration = $duration; } public function cost() { return $this->_costStrategy->cost($this); } public function chargeType() { return $this->_costStrategy->chargeType($this); } public function getDuration() { return $this->_duration; } public function getCostStrategy() { return $this->_costStrategy; } } class Lecture extends Lesson { } class Seminar extends Lesson { } abstract class CostStrategy { abstract function cost(Lesson $lesson); abstract function chargeType(); } class FixedCostStrategy extends CostStrategy { public function cost(Lesson $lesson){ return $lesson->getDuration * 5; } public function chargeType() { return 'Fixed rate'; } } class HourCostStrategy extends CostStrategy { public function cost(Lesson $lesson){ return 30; } public function chargeType() { return 'Hour rate'; } } /*$lectur = new Lecture(50, Lesson::FIXED); $sminar = new Seminar(50, Lesson::TIMED); print_r($lectur->cost() . $lectur->chargeType());//输出 print_r($sminar->cost() . $lectur->chargeType());//输出*/ $lecture = new Lecture(5,(new FixedCostStrategy())); var_dump($lecture->getCostStrategy()->chargeType());