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.

226<br />

CHAPTER 16 ■ THE COMMAND PATTERN<br />

Next, you need two classes, one for encapsulating the start method of the ad, and another<br />

for encapsulating the stop method:<br />

/* StopAd command class. */<br />

var StopAd = function(adObject) { // implements AdCommand<br />

this.ad = adObject;<br />

};<br />

StopAd.prototype.execute = function() {<br />

this.ad.stop();<br />

};<br />

/* StartAd command class. */<br />

var StartAd = function(adObject) { // implements AdCommand<br />

this.ad = adObject;<br />

};<br />

StartAd.prototype.execute = function() {<br />

this.ad.start();<br />

};<br />

These are very typical command classes. They take another object as an argument to the<br />

constructor and implement an execute method that calls one particular method of that object.<br />

There are now two classes with identical interfaces that can be used in the UI. You don’t know<br />

or care what the concrete implementation of adObject is; as long as it implements start and<br />

stop methods, it will work. The command pattern allows you to decouple the UI objects from<br />

the ad objects.<br />

To show how this works, the following UI has two buttons for each ad in the user’s<br />

account, one that starts the ad rotation, and another that stops it:<br />

/* Implementation code. */<br />

var ads = getAds();<br />

for(var i = 0, len = ads.length; i < len; i++) {<br />

// Create command objects for starting and stopping the ad.<br />

var startCommand = new StartAd(ads[i]);<br />

var stopCommand = new StopAd(ads[i]);<br />

// Create the UI elements that will execute the command on click.<br />

new UiButton('Start ' + ads[i].name, startCommand);<br />

new UiButton('Stop ' + ads[i].name, stopCommand);<br />

}<br />

The UiButton class constructor takes a button label and a command object. It then creates<br />

a button on the page that invokes the command’s execute method when clicked. This is another<br />

module that doesn’t need to know the exact implementation of the command objects being<br />

used. Because every command implements an execute method, you could pass in any kind of<br />

command and the UiButton class would know how to interact with it. This allows the creation<br />

of very modular and decoupled user interfaces.

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

Saved successfully!

Ooh no, something went wrong!