03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 12 ■ THE DECORATOR PATTERN 171<br />

throw new Error('Decorator ' + options[i].name + ' not found.');<br />

}<br />

var argument = options[i].arg;<br />

bicycle = new decorator(bicycle, argument);<br />

}<br />

// Check the interface and return the finished object.<br />

Interface.ensureImplements(bicycle, Bicycle);<br />

return bicycle;<br />

};<br />

// Model name to class name mapping.<br />

AcmeBicycleShop.models = {<br />

'The Speedster': AcmeSpeedster,<br />

'The Lowrider': AcmeLowrider,<br />

'The Flatlander': AcmeFlatlander,<br />

'The Comfort Cruiser': AcmeComfortCruiser<br />

};<br />

// Option name to decorator class name mapping.<br />

AcmeBicycleShop.options = {<br />

'headlight': HeadlightDecorator,<br />

'taillight': TaillightDecorator,<br />

'bell': BellDecorator,<br />

'basket': BasketDecorator,<br />

'color': FrameColorDecorator,<br />

'lifetime warranty': LifetimeWarrantyDecorator,<br />

'timed warranty': TimedWarrantyDecorator<br />

};<br />

If order is important, you can add code to sort the options array before you use it to<br />

instantiate the decorators.<br />

Using a factory to instantiate the bicycle object provides a couple of important benefits.<br />

First, you don’t have to keep track of all of the different class names for the bicycles and decorators;<br />

all of that is encapsulated in the AcmeBicycleShop class. This means you can add<br />

bicycle models and options very easily just by adding them to the AcmeBicycleShop.models<br />

or AcmeBicycleShop.options arrays. To illustrate this, let’s take a look at two different ways of<br />

creating a decorated bicycle object. The first way will not use the factory:<br />

var myBicycle = new AcmeSpeedster();<br />

myBicycle = new FrameColorDecorator(myBicycle, 'blue');<br />

myBicycle = new HeadlightDecorator(myBicycle);<br />

myBicycle = new TaillightDecorator(myBicycle);<br />

myBicycle = new TimedWarrantyDecorator(myBicycle, 2);<br />

By instantiating the objects directly, you are now tightly coupled to no less than five<br />

separate classes. The second way uses the factory and is coupled to only one class, the<br />

factory itself:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!