Using the Decorator Pattern for a Real Web Site (Page 1 of 6 )
Dynamic Selection of Concrete Components and Decorations: A Hybrid Car Dealership
Up to this point, the examples have focused on different dimensions of the Decorator design pattern, with the emphasis on how the different elements in the Decorator design pattern can be used with different components and decorations. Both concrete and abstract output has shown different ways to display information, but no example has illustrated how to input data dynamically. This Decorator example uses the case of selecting automobiles and their options to illustrate how to dynamically input data for both decorators and concrete components.
Imagine that you are responsible for creating and maintaining a web site for a car dealership. With each year, new models appear, and different options are made available. You never know what options are going to be added or dropped, or even if the same car models will be around from one year to the next. You’ve decided to use the Decorator pattern because you can easily add or drop both concrete components and concrete decorators. The concrete components will be the different models, and the options are the different decorations for any model selected. So whenever a new model appears, you simply update the concrete component to reflect those changes. Likewise with the options available for any of the models, all you need to change are the concrete decorations. You can easily add or change decorations without altering the program’s basic structure.
Setting Up the Hybrid Car Components
This particular dealership has decided to specialize in four hybrid model cars. This example uses four such cars, the Prius, Mercury Mariner, Ford Escape and Honda Accord hybrids. So in addition to an abstract Component class, this example requires four concrete components.
Auto abstract component
To get started, the abstract component is cast as a class named Auto. It needs only a string for the name of the car and a numeric variable for the car’s price. Two getter functions for auto type and price make up the rest of the abstract component. Example 4-38 shows the code saved asAuto.as.
Example 4-38. Auto.as
package { //Abstract class public class Auto { protected var information:String; protected var bucks:Number;
public function getInformation():String { return information; } public function price():Number { return bucks; } } }
As with all Decorator design patterns, all other classes are derived from this abstract component class. In the next section, you’ll see that all of the concrete component classes are subclasses of theAutoclass.