Extended Example: Sharing Command Objects | 265
Sharing Command Objects from the Client
Now that the keyboard invoker has been implemented, we can add the following at
the end of the client code shown in Example 7-18. This creates a new
InvokerKeyboardinstance, and assigns the same command objects to it that were
used for theInvokerPanel.
var kb:InvokerKeyboard = new InvokerKeyboard(this.stage);
// add commands to keyboard shortcut invoker
kb.setCommand(Keyboard.RIGHT, incCommand);
kb.setCommand(Keyboard.LEFT, decCommand);
kb.setCommand(Keyboard.NUMPAD_ADD, incCommand);
kb.setCommand(Keyboard.NUMPAD_SUBTRACT, decCommand);
The keyboard right arrow key and the plus key on the numeric keypad should per-
form the increment command. Conversely, the left arrow key and negative key on
the numeric keypad should perform the decrement command.
Command sharing is a powerful feature of the command pattern and makes extend-
ing applications much easier to manage. For example, if we decide to use a different
receiver, we just need to pass an instance of the new receiver when creating the com-
mand object. Because the same command object is used in multiple invokers, the
public function InvokerKeyboard(stageTarget:Stage)
{
this.commandList = new Array( );
this.keyList = new Array( );
stageTarget.addEventListener(KeyboardEvent.KEY_DOWN,
this.onKeyPress);
}
public function setCommand(keycode:int, c:ICommand):void
{
this.keyList.push(keycode);
this.commandList.push(c);
}
private function onKeyPress(event:KeyboardEvent)
{
for (var i:int = 0; i < keyList.length; i++)
{
if (keyList[i] === event.keyCode)
{
this.commandList[i].execute( );
break;
}
}
}
}
}
Example 7-19. InvokerKeyboard.as (continued)