Datasheet

24
x
CHAPTER 1 INTRODUCING SYMFONY, CAKEPHP, AND ZEND FRAMEWORK
echo ‘Driving the car without decoration: <br />’;
echo $car->drive() . ‘<br />’;
?>
code snippet /decorator/Test.php
And the result will be the following:
Driving standard car:
Accelerating. Remember to shift up. Driving comfort is standard.
Driving fully decorated car:
Accelerating. Auto transmission shifts up. Driving comfort is very high.
Driving the car without decoration:
Accelerating. Auto transmission shifts up. Driving comfort is standard.
First we call the basic Car model. Next we install the optional equipment and call the drive()
function of the
CarDecorator. Finally we choose to drive the car not using the Decorator wrap-
ping. Note that after calling the
$car then, its transmission is still automatic. That’s because the
Decorator changed it permanently.
Going back to frameworks, the Decorator pattern is used among others for layouts and templates. It is
very useful for adding optional visual components or extending the user interface when new widgets
are needed. An example may be adding scrollbars when user input exceeds the fi eld area.
Chain of Responsibility
The three preceding design patterns concerned object creation and inheritance structure. Chain
of Responsibility is a pattern of another kind, because it applies to the behavior of objects. Its
main intent is to decouple the sender of a request from its receiver. Let’s see how it works with an
automotive example.
Imagine that there is an emergency on the road and you
need to quickly stop the car. In other words,
stop is the
emitted request. In most cases, hitting the brake pedal is a
suf cient solution, but there are rare cases when you fi nd
the brakes broken; that’s when Chain of Responsibility
comes in handy. If brakes cannot handle the request, they
pass it to the handbrake. If for any reason the handbrake is
broken, too, and you are going to hit the obstacle, at least
airbags should open potentially saving your life. Airbags
are the most generic solution to most road emergencies.
They are less preferred than more specialized solutions
(braking, evading), but still better than nothing if those
maneuvers fail. It’s the same with your applications — it is
better to give the request a chain of potential handlers, as
shown in Figure 1-23, instead of letting it fail without even
an error message.
Client
Processing
element
Processing
element
Processing
element
Processing
element
Request
FIGURE 123: Chain of Responsibility as a
response to a request
c01.indd 24c01.indd 24 1/24/2011 5:45:21 PM1/24/2011 5:45:21 PM