我正在阅读PHP对象,模式和实践。作者正试图在大学里模拟一堂课。目标是输出课程类型(讲座或研讨会),并且该课程的费用取决于它是每小时课程还是固定价格课程。所以输出应该是
Lesson charge 20. Charge type: hourly rate. Lesson type: seminar.
Lesson charge 30. Charge type: fixed rate. Lesson type: lecture.
当输入如下时:
$lessons[] = new Lesson('hourly rate', 4, 'seminar');
$lessons[] = new Lesson('fixed rate', null, 'lecture');
我这样写:
class Lesson {
private $chargeType;
private $duration;
private $lessonType;
public function __construct($chargeType, $duration, $lessonType) {
$this->chargeType = $chargeType;
$this->duration = $duration;
$this->lessonType = $lessonType;
}
public function getChargeType() {
return $this->getChargeType;
}
public function getLessonType() {
return $this->getLessonType;
}
public function cost() {
if($this->chargeType == 'fixed rate') {
return "30";
} else {
return $this->duration * 5;
}
}
}
$lessons[] = new Lesson('hourly rate', 4, 'seminar');
$lessons[] = new Lesson('fixed rate', null, 'lecture');
foreach($lessons as $lesson) {
print "Lesson charge {$lesson->cost()}.";
print " Charge type: {$lesson->getChargeType()}.";
print " Lesson type: {$lesson->getLessonType()}.";
print "<br />";
}
但是根据这本书,我错了(我也很确定自己也错了)。相反,作者给出了较大的类层次结构作为解决方案。在上一章中,作者说了以下“四个路标”,这是我考虑更改班级结构的时间:
我能看到的唯一问题是条件语句,而且也含糊其词-那么为什么要重构呢?您认为我未曾预见的将来会出现什么问题?
更新:我忘了提-这是作者提供的类结构作为解决方案- 策略模式: