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 16<br />

■ ■ ■<br />

The Command Pattern<br />

In this chapter, we take a look at a way to encapsulate the invocation of a method. The command<br />

pattern is different from a normal function in several ways: it provides the ability to<br />

parameterize and pass around a method call, which can then be executed whenever you need<br />

it to be. It also allows you to decouple the object invoking the action from the object implementing<br />

it, thus providing a huge degree of flexibility in swapping out concrete classes. The<br />

command pattern can be used in many different situations, but it is very useful in creating<br />

user interfaces, especially when an unlimited undo action is required. This pattern can also be<br />

used in place of a callback function, as it allows greater modularity in passing the action from<br />

object to object.<br />

In the next few sections, we discuss the structure of the command pattern and give several<br />

examples of how it can be used in JavaScript. We also cover the best places to use command<br />

objects, and the situations where they should not be used.<br />

The Structure of the Command<br />

In its simplest form, a command object binds together two things: an action, and an object that<br />

may wish to invoke that action. All command objects have one thing in common: an execute<br />

operation, which invokes the action it is bound to. In most command objects, this operation is<br />

a method called execute or run. All command objects that use the same interface can be treated<br />

identically and can be swapped at will. This is part of the appeal of the command.<br />

To show how the command pattern is typically used, we will walk through an example about<br />

a dynamic user interface. Imagine you have an advertising company, and you wish to create<br />

a web page that will allow customers to perform certain actions in regard to their accounts, such<br />

as starting and stopping particular ads from running. It’s not known how many ads there will be,<br />

so you want to create a user interface (UI) that is as flexible as possible. To do this, you will use the<br />

command pattern to loosely couple UI elements, such as buttons, with actions.<br />

First, you need an interface that all commands must respond to:<br />

/* AdCommand interface. */<br />

var AdCommand = new Interface('AdCommand', ['execute']);<br />

225

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

Saved successfully!

Ooh no, something went wrong!