PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 8 ■ SOME PATTERN PRINCIPLES


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( );
}


function getDuration() {
return $this->duration;
}


// more lesson methods...
}


class Lecture extends Lesson {
// Lecture-specific implementations ...
}


class Seminar extends Lesson {
// Seminar-specific implementations ...
}


The Lesson class requires a CostStrategy object, which it stores as a property. The Lesson::cost()
method simply invokes CostStrategy::cost(). Equally, Lesson::chargeType() invokes
CostStrategy::chargeType(). This explicit invocation of another object’s method in order to fulfill a
request is known as delegation. In my example, the CostStrategy object is the delegate of Lesson. The
Lesson class washes its hands of responsibility for cost calculations and passes on the task to a
CostStrategy implementation. Here, it is caught in the act of delegation:


function cost() {
return $this->costStrategy->cost( $this );
}


Here is the CostStrategy class, together with its implementing children:

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() {

Free download pdf