Dynamic Selection of Concrete Components and Decorations: A Hybrid Car Dealership | 165
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 namedAuto. 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;
}
}
}