Saturday, February 26, 2011

Command Pattern

The command pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.

 

Command_Design_Pattern_Class_Diagram

Following are some of the steps

1. Client creates Command object.

   a. Command object has execute() method

      i. Execute() method has calls to action1() and action2() methods of the Receiver object

2. Invoker object has a setCommand(Command obj) method (parameterizing an object)

3. Client calls setCommand() on the Invoker object.

4. Invoker calls execute() method of the Command object.

5. Command object then calls action1() and action2() methods of the Receiver object.

 

For example:
public interface Command {
   public void execute() ;
}

public class LightOnCommand implements Command {
   Light light;
   public LightOnCommand(Light light) {
      this. light = light;
   }
   public void execute() {
      light. on() ;
   }
}

public class SimpleRemoteControl {
   Command slot;
   public SimpleRemoteControl() { }
   public void setCommand( Command command) {
      slot = command;
   }
   public void buttonWasPressed() {
      slot. execute() ;
   }
}

public class RemoteControlTest {
   public static void main( String[ ] args) {
      SimpleRemoteControl remote = new SimpleRemoteControl() ;
   Light light = new Light() ;
   LightOnCommand lightOn = new LightOnCommand(light) ;
   remote. setCommand(lightOn) ;
   remote. buttonWasPressed() ;
   }
}

No comments:

Total Pageviews

Popular Posts