Friday, July 4, 2014

Command Design Pattern

 

Implementing the Command interface

First things first: all command objects implement the same interface, which consists of one method.

here's the Command interface:

 public interface Command{  
   public void execute();  
 }  

Implementing a Command to turn a light on

Now, let's say you want to implement a command for turning a light on.
Referring to our set of vendor classes, the Light class has two methods: on() and off(). Here's how you can implement this as a command:


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

Using the command object

Okey, let's make things simple: say we've got a remote control with only one button and corresponding slot to hold a device to control:


public class SimpleRemoteControl{  
   //we have one slot to hold our command which will control one device.  
   Command slot;  
   public SimpleRemoteControl(){}  
   //we have a method for setting the command the slot is going to control.   
   //This could be called multiple times if the client of this code wanted   
   //to change the behavior of the remote button.  
   public void setCommand(Command command){  
     slot=command;  
   }  
   //This method is called when the button is pressed .   
   //All we do take the current command bound to the slot and  
   //call its execute() method.  
   public void buttonWasPressed(){  
     slot.execute();  
   }  
 }

Creating a simple test to use the Remote Control

Here's just a bit of code to test out the simple remote control. Let's take a look and we'll point out how the pieces match the Command Pattern diagram:


//This is our client in Command pattern-speak.  
 public class RemoteControlTest{  
   public static void main(String[] args){  
     //The remote is our invoker; it will be passed a command object that can be used to make  
     //requests.  
     SimpleRemoteControl remote = new SimpleRemoteControl();  
     //Now we create a Light object, this will be the Receiver of the request.  
     Light light= new Light();  
     //Here, creates a Command and pass it to the Receiver.  
     LightOnCommand lightOn=new LightOnCommand(light);  
     remote.setCommand(lightOn);//Here, pass the command to the invoker.  
     remote.buttonWasPressed();//And then we simulate the button being pressed.  
   }  
 }  

No comments:

Post a Comment

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code