PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 10 ■ PATTERNS FOR FLEXIBLE OBJECT PROGRAMMING


Notice the new getComposite() method. I will return to this in a little while. Now, I need a new
abstract class to hold addUnit() and removeUnit(). I can even provide default implementations:


abstract class CompositeUnit extends Unit {
private $units = array();


function getComposite() {
return $this;
}


protected function units() {
return $this->units;
}


function removeUnit( Unit $unit ) {
$this->units = array_udiff( $this->units, array( $unit ),


function( $a, $b ) { return ($a === $b)?0:1; } );


}


function addUnit( Unit $unit ) {
if ( in_array( $unit, $this->units, true ) ) {
return;
}
$this->units[] = $unit;
}
}


The CompositeUnit class is declared abstract, even though it does not itself declare an abstract
method. It does, however, extend Unit, and does not implement the abstract bombardStrength() method.
Army (and any other composite classes) can now extend CompositeUnit. The classes in my example are
now organized as in Figure 10–2.

Free download pdf