<?php abstract class Lesson{ private $duration; private $costStrategy; function __construct( $duration, CostStrategy $strategy) { $this->duration = $duration; $this->costStrategy = $strategy; } function cost() { return $this->costStrategy->cost( $this ); } function chargeType() { return $this->costStrategy->chargeType( $this ); } function getDuration() { return $this->duration; } } class Lecture extends Lesson{ //lecrure 特定的方法 } class Seminar extends Lesson{ //seminar 特定的方法 } abstract class CostStrategy{ abstract function cost( Lesson $lesson); abstract function chargeType(); }
//以下有不同的计费方式
class TimedCostStrategy extends CostStrategy{
//计费方式一 function cost( Lesson $lesson) { return $lesson->getDuration()*5; } function chargeType() { return "hourly rate"; } } class FixedCostStrategy extends CostStrategy{
//计费方式二 function cost( Lesson $lesson) { return 30; } function chargeType() { return "fixed rate"; } }
$lessons[] = new Seminar(4, new TimedCostStrategy() );
$lessons[] = new Lecture(4, new FixedCostStrategy() );
foreach ($lessons as $lesson) {
print " lesson charge {$lesson->cost}";
print " Charge type: {$lesson->chargeType()}
";
}
通过传递不同的CostStrategy对象,来改变Lesson对象的计算费用方式