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.

98<br />

CHAPTER 7 ■ THE FACTORY PATTERN<br />

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

return bicycle;<br />

};<br />

/* GeneralProductsBicycleShop class. */<br />

var GeneralProductsBicycleShop = function() {};<br />

extend(GeneralProductsBicycleShop, BicycleShop);<br />

GeneralProductsBicycleShop.prototype.createBicycle = function(model) {<br />

var bicycle;<br />

switch(model) {<br />

case 'The Speedster':<br />

bicycle = new GeneralProductsSpeedster();<br />

break;<br />

case 'The Lowrider':<br />

bicycle = new GeneralProductsLowrider();<br />

break;<br />

case 'The Flatlander':<br />

bicycle = new GeneralProductsFlatlander();<br />

break;<br />

case 'The Comfort Cruiser':<br />

default:<br />

bicycle = new GeneralProductsComfortCruiser();<br />

}<br />

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

return bicycle;<br />

};<br />

All of the objects created from these factory methods respond to the Bicycle interface, so any<br />

code written can treat them as being completely interchangeable. Selling bicycles is done in the<br />

same way as before, only now you can create shops that sell either Acme or General Products bikes:<br />

var alecsCruisers = new AcmeBicycleShop();<br />

var yourNewBike = alecsCruisers.sellBicycle('The Lowrider');<br />

var bobsCruisers = new GeneralProductsBicycleShop();<br />

var yourSecondNewBike = bobsCruisers.sellBicycle('The Lowrider');<br />

Since both manufacturers make bikes in the same styles, customers can go into a shop<br />

and order a certain style without caring who originally made it. Or if they only want an Acme<br />

bike, they can go to the shops that only sell Acme bikes.<br />

Adding additional manufacturers is easy; simply create another subclass of BicycleShop<br />

and override the createBicycle factory method. You can also modify each subclass to allow for<br />

additional models specific to a certain manufacturer. This is the most important feature of the<br />

factory pattern. You can write all of your general Bicycle code in the parent class, BicycleShop,<br />

and then defer the actual instantiation of specific Bicycle objects to the subclasses. The general<br />

code is all in one place, and the code that varies is encapsulated in the subclasses.

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

Saved successfully!

Ooh no, something went wrong!