The Command Pattern

http://www.wired.com/2009/03/rf-remote-contr/

I had one more pattern to look into for my iteration this week and the one that was suggested to me by a crafter was the Command Pattern. This pattern allows you to execute a method of an object that is wrapped in another command class, so when this command class is invoked by a client the receiver is executed. This allows for the execution to be delayed and even placed in a queue if necessary. It passes the responsibility of executing a command from the receiver to the command class.

An example of a remote control is a good one because it can handle an object that is executable and can be turned on and off (a light for example).

If there is a simple light …

public class Light {
private String roomLight;

public Light(String roomLight) {
this.roomLight = roomLight;
}

public String on() {
return "Light in the " + roomLight + " is On";
}

public String off() {
return "Light in the " + roomLight + " is Off";
}
}

.. it can be given to a LightOnCommand..

public class LightOnCommand implements Command {
Light light;

public LightOnCommand(Light light) {
this.light = light;
}

@Override
public String execute() {
return light.on();
}
}

or LightOffCommand…

public class LightOffCommand implements Command {
Light light;

public LightOffCommand(Light light) {
this.light = light;
}

@Override
public String execute() {
return light.off();
}
}

The remote control class then can add multiple commands to its on and off buttons. These can be initially set to empty commands (new NoCommand()) and then set accordingly, using the Null Object Pattern.

This means that anytime a slot’s on and off buttons are set, it is possible to “push” the corresponding button and have the command execute the on or off for the item it holds.

This pattern encapsulates the request of an action and decouples the requester from the invoker. A really useful pattern to know.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.