Datasheet
DESIGN PATTERNS IN WEB FRAMEWORKS
x
21
echo ‘Fine, we will paint your ‘.$customersCar->getModel().
‘ ‘.$customersCar->getColor().’.<br />’;
?>
code snippet /prototype/Test.php
The previous code will result in the following messages:
Which car do you want?
Subaru Outback.
What color do you want?
Fine, we will paint your Subaru Outback red.
The Prototype pattern is used commonly in different modules of frameworks. An example can be
nesting of forms within forms in Symfony or the
AppController class of CakePHP.
Decorator
Subclassing is a great mechanism, but it has some serious limitations. Suppose that you want to pro-
duce a car. You put all your effort into designing a good yet affordable standard model of the car. It
is a complete design that defi nes the look and feel of this model and it is a reference for any possible
modifi cations. Then you seek to provide some optional equipment that improves the quality of the
car and adds some new functionalities. For example, it may be all-wheel drive instead of front-wheel
drive. It may be automatic transmission instead of manual. The car may also come in different trim
levels with electric leather seats, sunroof, better audio, or GPS satellite navigation. However the
basic interface remains the same — you can drive this car and feel good doing it.
When you face such alternatives, the number of possible combinations rises really fast. Figure 1-21
shows some combinations for just three improvements, described as inheritance hierarchy.
+drive()
Car_with_AutoTransmission_and_Sunroof_and_GPS
Car_with_AutoTrasmission_and_Sunroof
Car_with_GPS
Car_with_Sunroof
Car_with_AutoTransmission
Car
FIGURE 121: Nasty inheritance hierarchy
The answer to this problem is the Decorator pattern. The Decorator is a class that shares the inter-
face with the decorated class (in our example, it is the basic car). It encapsulates an instance of the
c01.indd 21c01.indd 21 1/24/2011 5:45:20 PM1/24/2011 5:45:20 PM