Aug 6, 2008

Command Pattern

The Command Pattern allows a client to issue requests (commands) to an object without making any assumptions about the request or the receiving object (receiver). This is done by decoupling the client from the receiver by including an invoker.


Command Interface:

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

Concrete Command:

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


Receiver:

package
{
    public class Receiver
    {
        public function action ()
        {
            trace ("Receiver doing action.");
        }
    }
}

Invoker:

package
{
    public class Invoker
    {
        var currentCommand:ICommand;
      
        public function setCommand (c:ICommand):void
        {
            currentCommand = c;
        }
      
        public function executeCommand ():void
        {
            currentCommand.execute ();
        }
    }
}

Client:

package
{
    import flash.display.MovieClip;
  
    public class Main
    {
        public function Main ():void
        {
            var rec:Receiver = new Receiver ();
            var concCommand:ICommand = new ConcreteCommand (rec);
            var invoker:Invoker = new Invoker ();
            invoker.setCommand (concCommand);
            concCommand.execute ();
        }
    }
}