Datasheet
22
x
CHAPTER 1 INTRODUCING SYMFONY, CAKEPHP, AND ZEND FRAMEWORK
decorated object and extends its responsibilities dynamically. It is like putting a gift into a solid box
and then wrapping it with colorful paper — it is still a gift, but durable and decorated. The inheri-
tance structure of the Decorator pattern is presented in Figure 1-22.
+drive()
+drive()
«interface»
Driveable
AutoTransmissionDecorator
GPSDecorator SunroofDecorator
Car
+drive()
CarDecorator
FIGURE 122: More reasonable inheritance hierarchy with Decorator
You can put the decorated object into other Decorators without limitations. This way you can add
as many optional modules as you wish. Decorators can have their own inheritance hierarchy, and
within this hierarchy they encapsulate the core object recursively.
The code below creates a standard
Car class without optional equipment.
<?php
class Car{
public $gearMessage = ‘Remember to shift up.’;
public $comfortMessage = ‘standard.’;
function drive() {
return ‘Accelerating ‘ . $this->gearMessage .
‘ Driving comfort is ‘ . $this->comfortMessage;
}
}
?>
code snippet /decorator/Car.class.php
The following classes are responsible for extending the functionality of the car. The fi rst one,
CarDecorator, is the fi rst level of wrapping. It stores the $car variable and a copy of $comfortMessage.
This variable will be changed by a Decorator, so we create a copy to avoid changing the original
$car
object. On the other hand,
$gearMessage is changed internally. The drive() function is also sub-
classed to use the proper variables
$car->model and $this->gearMessage because we want to access
the core object here, but
$this->comfortMessage because we want to use the amended value.
Second-level Decorators wrapping the
CarDecorator are used to install optional components, as
shown below.
AutomaticTransmissionDecorator installs the $gearMessage directly into the core
$car, but GPSDecorator is installed into the CarDecorator instead. Note that all decorators share
the common interface and additionally provide specifi c installers.
c01.indd 22c01.indd 22 1/24/2011 5:45:20 PM1/24/2011 5:45:20 PM