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