06.07.2017 Views

Mastering JavaScript

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

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

<strong>JavaScript</strong> Patterns<br />

Let's take a common example to understand the usage of a factory. Let's say that we<br />

have the following:<br />

• A constructor, CarFactory()<br />

• A static method in CarFactory called make() that knows how to create<br />

objects of the car type<br />

• Specific car types such as CarFactory.SUV, CarFactory.Sedan, and so on<br />

We want to use CarFactory as follows:<br />

var golf = CarFactory.make('Compact');<br />

var vento = CarFactory.make('Sedan');<br />

var touareg = CarFactory.make('SUV');<br />

Here is how you would implement such a factory. The following implementation<br />

is fairly standard. We are programmatically calling the constructor function that<br />

creates an object of the specified type—CarFactory[const].prototype = new<br />

CarFactory();.<br />

We are mapping object types to the constructors. There can be variations in how you<br />

can go about implementing this pattern:<br />

// Factory Constructor<br />

function CarFactory() {}<br />

CarFactory.prototype.info = function() {<br />

console.log("This car has "+this.doors+" doors and a<br />

"+this.engine_capacity+" liter engine");<br />

};<br />

// the static factory method<br />

CarFactory.make = function (type) {<br />

var constr 0= type;<br />

var car;<br />

CarFactory[constr].prototype = new CarFactory();<br />

// create a new instance<br />

car = new CarFactory[constr]();<br />

return car;<br />

};<br />

CarFactory.Compact = function () {<br />

this.doors = 4;<br />

this.engine_capacity = 2;<br />

};<br />

[ 132 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!