下面代码是书上例子,在php下运行也没错误,但有几点不解
1.abstract 抽象类 里面竟然没有抽象方法?
2. function __construct( $duration, CostStrategy $strategy ) {
还有这种传递方式?我仔细看了一下,应该是把下面声明的抽象类CostStrategy以别名方式传进来,是这样吗,如果是真的,抽象类CostStrategy都不需要被继承吗?
这段代码把我搞糊涂了
duration = $duration;
$this->costStrategy = $strategy;
}
function cost() {
return $this->costStrategy->cost( $this );
}
function chargeType() {
return $this->costStrategy->chargeType( );
}
function getDuration() {
return $this->duration;
}
// more lesson methods...
}
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";
}
}
class Lecture extends Lesson {
// Lecture-specific implementations ...
}
class Seminar extends Lesson {
// Seminar-specific implementations ...
}
$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()}\n";
}
?>
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
ringa_lee