O'Reilly logo

ActionScript 3.0 Design Patterns by Chandima Cumaranatunge, William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Minimalist Example of a Command Pattern

This example implements the command pattern class diagram in Figure 7-3. The command pattern consists of the command interface, concrete commands that implement the command interface, invokers that call the execute() method in concrete commands, receivers that implement the behavior required of commands, and clients that create concrete commands and pass them on to invokers.

Code examples Example 7-1 through Example 2-7 show the minimalist implementation of the command pattern.

The Command Interface

Example 7-1 shows the ICommand class that defines the interface for commands. It defines a single method called execute().

Example 7-1. ICommand.as

package
{
    public interface ICommand {
        function execute():void;
    }
}

The Concrete Command

Example 7-2 shows the ConcreteCommand class that implements the ICommand interface. The parameterized constructor takes a Receiver class instance and assigns it to the receiver property. The execute() command is implemented by delegating to the receiver instance by calling its action() method. Note that, because the receiver instance is passed to the constructor, the ConcreteCommand class and Receiver class are loosely coupled, allowing a subclass of Receiver to be passed if needed.

Example 7-2. ConcreteCommand.as

package { class ConcreteCommand implements ICommand { var receiver:Receiver; public function ConcreteCommand(rec:Receiver):void { this.receiver = rec; } public function execute():void { receiver.action(); } } } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required