ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Example of a Command Pattern | 253

The Client


Example 7-5 shows theMainclass (also thedocument classfor the Flash document)


that represents theclient. The client does several tasks. It first creates an instance of


thereceiver(line 9) and passes it as a parameter when creating aConcreteCommand


instance (line 10). The instance ofConcreteCommandis called acommand object. The


client then creates an instance of theInvokerclass (line 12) and passes the command


object to it (line 13). Finally, the client executes the command by calling the


execute( ) method on the command object.


The output from the minimalist application will be the following trace from the


receiver object indicating that itsaction( ) method has been called:


Receiver: doing action

Example 7-4. Invoker.as


package
{
class Invoker
{
var currentCommand:ICommand;


public function setCommand(c:ICommand):void
{
this.currentCommand = c;
}


public function executeCommand( )
{
currentCommand.execute( );
}
}
}


Example 7-5. Main.as


1 package
2 {
3 import flash.display.MovieClip;
4
5 public class Main extends MovieClip
6 {
7 public function Main( )
8 {
9 var rec:Receiver = new Receiver( );
10 var concCommand:ICommand = new ConcreteCommand(rec);
11
12 var invoker:Invoker = new Invoker( );
13 invoker.setCommand(concCommand);
14 concCommand.execute( ); // execute command
15 }
16 }
17 }
Free download pdf