Spring 2010ACS-3913 Ron McFadyen1 Command The command pattern encapsulates a request or unit of work into an object. An invoker will ask a concrete command to perform its function and the concrete command will in turn ask some receiver to perform a pre-determined action.
Fall 2008ACS-3913 Ron McFadyen2 Command Example: User interfaces typically give you ways to issue a particular command Java Swing classes use the command pattern to perform application-specific functionality. Action objects are used. Button classes, menu items, etc. maintain a reference to an action defined by the Action interface. Whenever a Swing component activates, it calls its action’s (command’s) actionPerformed() method (execute() method).
Spring 2010ACS-3913 Ron McFadyen3 Command – generic class diagram «Interface» Command Concrete Command Receiver Invoker Command Concrete commandreceiver command action1() action2() execute() setCommand() invoker
Spring 2010ACS-3913 Ron McFadyen4 Command – simple example Remote Control off A remote control with two buttons : one to turn a light on, the other to turn a light off on
Spring 2010ACS-3913 Ron McFadyen5 Command – text example «Interface » Command lightOn Command Light Remote control Command Concrete command receiver command on() off() execute() setCommand() invoker lightOff Command execute() Concrete command
Spring 2010ACS-3913 Ron McFadyen6 Command - behaviour :Light:RemoteControl execute() lightOn() execute() lightOff() :LightOn Command :LightOff Command