Command Design Pattern In Java
Join the DZone community and get the full member experience.
Join For FreeToday, I am here to discuss another behavioral design pattern called Command Design Pattern. A very useful pattern in which we wrap the request in an object known as Command and provide it an Invoker to perform.
Command Design Pattern
- In the Command Design Pattern, we wrap our requests in a Command object, along with all the required information to perform an action of another object.
- The Command object knows about the Receiver and invokes methods of the receiver by supplying parameters. Values for parameters of the receiver methods are stored in the Command object.
- The Receiver objects performs the job when the
execute()
method of Command gets called. - We pass this Command object to an Invoker object to perform the execute method. Invoker object executes the methods of the Command object and passes the required parameters to it.
- The Invoker objects knows how to execute the command. But, it does not know anything about any concrete command. All it knows about is the command interface/abstract class.
- The Invoker can take different Command objects time-to-time, so the Client deals only with the Invoker to perform operations on different objects. These objects call Receiver objects.
- The Command object collects all the details of requests and performs operations on the Receiver.
- The Command Design Pattern supports undoable operations as well and we can have an unexecute kind of method to return the state of the object back to its original state.
- So, the pattern makes it super easy to perform a verity of jobs/requests in a simple way by using Invoker object.
- The Invoker may also do bookkeeping for the Command objcets.
- Different Command object may have different Receiver object to act on.
- The execute method defines and performs all the operations in the sequence to complete the job.
- The Client Application knows when and in which order to execute the commands.
- The only drawback of this pattern is we end up creating many command classes.
So, as you can see that in the above diagram, we wrap the request in a Command object.
Take Command1 for some request. We give all the parameter values required by the Receiver object to perform the request into Command1. Then, we set this command to Invoker and Invoker triggers the command. Command1's execute method comes into the action and performs all the operations required on Receiver object in a define order. Client gets the output via Receiver. That's it! in simple words.
Now an example to explain it.
Home Automation Application using Command Design Pattern
Suppose we like to control our home appliances with the help of a Smart Remote. The Home Appliances will act as receiver here. Smart Remote will act as an invoker. Operations on the appliances will be concrete commands and Client will be our main application.
To make it little user-friendly, I am trying here to provide command as statement like
'turn on bedroomlight' or 'bedroomlight switch off'
Sounds interesting? Well its not that much difficult. All I am trying here is make it super easy and without using any third party libraries; only based on Java 8 (mainly lambda's).
I think you guess it write, we need keywords and a command interpreter which will help us to find the right command and home appliance to select and perform the operation.
So without wasting more time, here's the code.
Code for Appliance class:
xxxxxxxxxx
package org.trishinfotech.command.devices;
public abstract class Appliance implements Comparable<Appliance> {
protected String name;
protected boolean status;
public Appliance(String name) {
super();
if (name == null || name.trim().isEmpty()) {
new IllegalArgumentException("Appliance name is mandatory for Home Automation");
}
this.name = name;
}
public String name() {
return name;
}
// define operations for appliance
public void on() {
if (status) {
System.out.printf("'%s' is already turned on!\n", name);
} else {
status = true;
System.out.printf("Turning On '%s'\n", name);
}
}
public void off() {
if (!status) {
System.out.printf("'%s' is already turned off!\n", name);
} else {
status = false;
System.out.printf("Turning Off '%s'\n", name);
}
}
// Appliance should be compared only on name.
public int compareTo(Appliance other) {
return this.name.compareToIgnoreCase(other.name);
}
}
I have defined common operations like 'On' and 'Off' here.
Code for Fan class:
xxxxxxxxxx
package org.trishinfotech.command.devices;
public abstract class Fan extends Appliance {
public static int TOP_SPEED = 4;
public static int LOWEST_SPEED = 1;
protected int currentSpeed = 1;
public Fan(String name) {
super(name);
}
// define operations for fan
public void increase() {
if (currentSpeed < TOP_SPEED) {
currentSpeed++;
System.out.printf("Encreasing Speed of '%s' to '%d'.\n", name, currentSpeed);
} else {
System.out.printf("'%s' is already running at top speed!\n", name);
}
}
public void decrease() {
if (currentSpeed > LOWEST_SPEED) {
currentSpeed--;
System.out.printf("Decreasing Speed of '%s' to '%d'.\n", name, currentSpeed);
} else {
System.out.printf("'%s' is laready running at lowest speed!\n", name);
}
}
}
I have added operations like 'Increase' and 'Decrease' here and its a sub-type of Appliance.
Code for Light class:
xxxxxxxxxx
package org.trishinfotech.command.devices;
public abstract class Light extends Appliance {
public Light(String name) {
super(name);
}
}
No additional operations are needed since we already have 'On' and 'Off' defined.
Code for TV class:
xxxxxxxxxx
package org.trishinfotech.command.devices;
public abstract class TV extends Appliance {
public static int TOP_VOLUME = 30;
public static int LOWEST_VOLUME = 0;
public static int TOP_CHANNEL_NO = 999;
public static int LOWEST_CHANNEL_NO = 1;
protected int currentVolume = 1;
protected int currentChannel = 1;
protected int volumeWhenMute;
public TV(String name) {
super(name);
}
// define operations for TV
public void increaseVolume() {
if (currentVolume < TOP_VOLUME) {
currentVolume++;
System.out.printf("Encreasing volume of '%s' to '%d'.\n", name, currentVolume);
} else {
System.out.printf("'%s' is already on top volume!\n", name);
}
}
public void decreaseVolume() {
if (currentVolume > LOWEST_VOLUME) {
currentVolume--;
System.out.printf("Decreasing volume of '%s' to '%d'.\n", name, currentVolume);
} else {
System.out.printf("'%s' is already on mute!\n", name);
}
}
public void mute() {
if (currentVolume != LOWEST_VOLUME) {
volumeWhenMute = currentVolume;
currentVolume = 0;
System.out.printf("Putting '%s' on mute!\n", name);
} else {
currentVolume = volumeWhenMute;
System.out.printf("Unmuting '%s'. Setting volume back to '%d'!\n", name, currentVolume);
}
}
public void increaseChannel() {
if (currentChannel < TOP_CHANNEL_NO) {
currentChannel++;
System.out.printf("Encreasing channel of '%s' to '%d'.\n", name, currentChannel);
} else {
System.out.printf("'%s' is already showing channel '%d'!\n", name, currentChannel);
}
}
public void decreaseChannel() {
if (currentChannel > LOWEST_CHANNEL_NO) {
currentChannel--;
System.out.printf("Decreasing channel of '%s' to '%d'.\n", name, currentChannel);
} else {
System.out.printf("'%s' is already showing channel '%d'!\n", name, currentChannel);
}
}
}
I have added operations like 'Increase/Decrease Volume', 'Increase/Decrease Channel' and 'Sound Mute'.
Now lets create some classes to create actual home appliance objects. I am creating them as separate classes because bed-room-light need not to be same as kitchen light and may have some additional operations like setting color white or warm white or even multi-color. I am not adding that level of piece of code and encourage you to think on that. Also, you may enhance it for real IoT project using some controllers with raspberry pi or something similar and control your home appliances. Please search on the Net for more information. Also if you need, I can provide additional information on that.
Code for BedRoomFan class:
xxxxxxxxxx
package org.trishinfotech.command.devices.bedroom;
import org.trishinfotech.command.devices.Fan;
public class BedRoomFan extends Fan {
public BedRoomFan() {
super("BedRoomFan");
}
}
Code for BedRoomLight class:
xxxxxxxxxx
package org.trishinfotech.command.devices.bedroom;
import org.trishinfotech.command.devices.Light;
public class BedRoomLight extends Light {
public BedRoomLight() {
super("BedRoomLight");
}
}
Code for KitchenLight class:
xxxxxxxxxx
package org.trishinfotech.command.devices.kitchen;
import org.trishinfotech.command.devices.Light;
public class KitchenLight extends Light {
public KitchenLight() {
super("KitchenLight");
}
}
Code for Microwave class:
xxxxxxxxxx
package org.trishinfotech.command.devices.kitchen;
import org.trishinfotech.command.devices.Appliance;
public class Microwave extends Appliance {
public Microwave() {
super("Microwave");
}
}
Code for LivingRoomFan class:
xxxxxxxxxx
package org.trishinfotech.command.devices.livingroom;
import org.trishinfotech.command.devices.Fan;
public class LivingRoomFan extends Fan {
public LivingRoomFan() {
super("LivingRoomFan");
}
}
Code for LivingRoomLight class:
xxxxxxxxxx
package org.trishinfotech.command.devices.livingroom;
import org.trishinfotech.command.devices.Light;
public class LivingRoomLight extends Light {
public LivingRoomLight() {
super("LivingRoomLight");
}
}
Code for LivingRoomTV class:
xxxxxxxxxx
package org.trishinfotech.command.devices.livingroom;
import org.trishinfotech.command.devices.TV;
public class LivingRoomTV extends TV {
public LivingRoomTV() {
super("LivingRoomTV");
}
}
Now, when all the appliances are defined along with their operations, it's time to work on Command Design Pattern. The above appliance-classes will be our Receiver objects.
Code for Command abstract class.
xxxxxxxxxx
package org.trishinfotech.command;
import java.util.List;
import org.trishinfotech.command.devices.Appliance;
public abstract class Command {
protected String name;
protected Appliance appliance;
public Command(String name, Appliance appliance) {
super();
this.name = name;
this.appliance = appliance;
}
public Appliance appliance() {
return appliance;
}
public String name() {
return name;
}
public abstract void execute();
public abstract List<String> keywords();
}
Please note that I have provided additional methods like 'keywords'. This will help us while interpreting the command.
Now, the code for concrete command classes. Just to avoid creating many class files, I wrote them as as a public static nested classes inside a public class called Commands.
Code for Commands class:
xxxxxxxxxx
package org.trishinfotech.command.commands;
import java.util.Arrays;
import java.util.List;
import org.trishinfotech.command.Command;
import org.trishinfotech.command.devices.Appliance;
import org.trishinfotech.command.devices.Fan;
import org.trishinfotech.command.devices.TV;
import org.trishinfotech.command.devices.livingroom.LivingRoomTV;
public class Commands {
protected static String SWITCH = "switch";
protected static String TURN = "turn";
protected static String ON = "on";
protected static String OFF = "off";
protected static String START = "start";
protected static String STOP = "stop";
protected static String OPEN = "open";
protected static String CLOSE = "close";
protected static String UP = "up";
protected static String DOWN = "down";
protected static String STARTUP = "startup";
protected static String SHUTDOWN = "shutdown";
protected static String MUTE = "mute";
protected static String UNMUTE = "unmute";
protected static String PAUSE = "pause";
protected static String INCREASE = "increase";
protected static String DECREASE = "decrease";
protected static String RAISE = "raise";
protected static String LOWER = "lower";
protected static String HIGHER = "higher";
protected static String HIGH = "high";
protected static String LOW = "low";
protected static String SET = "set";
protected static String SHOW = "show";
protected static String CHANNEL = "channel";
protected static String VOLUME = "volume";
protected static String DISPLAY = "display";
public static class OnCommand extends Command {
public OnCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
appliance.on();
}
public List<String> keywords() {
return Arrays.asList(ON, START, STARTUP);
}
}
public static class OffCommand extends Command {
public OffCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
appliance.off();
}
public List<String> keywords() {
return Arrays.asList(OFF, STOP, SHUTDOWN);
}
}
public static class IncreaseSpeedCommand extends Command {
public IncreaseSpeedCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((Fan)appliance).increase();
}
public List<String> keywords() {
return Arrays.asList(UP, INCREASE, RAISE, HIGH, HIGHER);
}
}
public static class DecreaseSpeedCommand extends Command {
public DecreaseSpeedCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((Fan)appliance).decrease();
}
public List<String> keywords() {
return Arrays.asList(DOWN, DECREASE, LOW, LOWER);
}
}
public static class TVIncreaseVolumeCommand extends Command {
public TVIncreaseVolumeCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((TV)appliance).increaseVolume();
}
public List<String> keywords() {
return Arrays.asList(UP, INCREASE, RAISE, HIGH, HIGHER, VOLUME);
}
}
public static class TVIncreaseChannelCommand extends Command {
public TVIncreaseChannelCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((TV)appliance).increaseChannel();
}
public List<String> keywords() {
return Arrays.asList(UP, INCREASE, RAISE, HIGH, HIGHER, CHANNEL);
}
}
public static class TVDecreaseVolumeCommand extends Command {
public TVDecreaseVolumeCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((TV)appliance).decreaseVolume();
}
public List<String> keywords() {
return Arrays.asList(DOWN, DECREASE, LOW, LOWER, VOLUME);
}
}
public static class TVDecreaseChannelCommand extends Command {
public TVDecreaseChannelCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((TV)appliance).decreaseChannel();
}
public List<String> keywords() {
return Arrays.asList(DOWN, DECREASE, LOW, LOWER, CHANNEL);
}
}
public static class TVMuteCommand extends Command {
public TVMuteCommand(String name, Appliance appliance) {
super(name, appliance);
}
public void execute() {
((LivingRoomTV)appliance).mute();
}
public List<String> keywords() {
return Arrays.asList(MUTE, UNMUTE, PAUSE);
}
}
}
Please notice that I also provided keywords along with the concrete-commands to decode them correctly. I am using interpreter here to identifying the appliance and the command to perform. I will try to write another article on Interpreters to make this more clear for the audience.
Code for CommandInterpreter class :
xxxxxxxxxx
package org.trishinfotech.command;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class CommandInterpreter {
public static Optional<Command> interpretCommand(String commandStr) {
Optional<Command> command = Optional.empty();
if (commandStr != null && !commandStr.trim().isEmpty()) {
List<String> applianceNames = HomeAutomation.INSTANCE.applianceNames();
Optional<String> applianceName = findApplianceName(commandStr, applianceNames);
if (applianceName.isPresent()) {
List<Command> commands = HomeAutomation.INSTANCE.applianceCommands(applianceName.get());
command = findCommand(commandStr, commands);
}
}
return command;
}
private static Optional<Command> findCommand(String commandStr, List<Command> availableCommands) {
List<Command> matchingCommands = availableCommands.stream()
.filter(availableCommand -> hasMatchingKeywords(availableCommand, commandStr))
.collect(Collectors.toList());
matchingCommands.sort(new Comparator<Command>() {
public int compare(Command cmd1, Command cmd2) {
return Integer.compare(noOfMatch(cmd2, commandStr), noOfMatch(cmd1, commandStr));
}
private int noOfMatch(Command cmd, String commandStr) {
return cmd.keywords().stream().filter(keyword -> hasPotentialMatch(keyword, commandStr)).collect(Collectors.toList()).size();
}
});
return Optional.ofNullable(matchingCommands.isEmpty() ? null : matchingCommands.get(0));
}
private static boolean hasMatchingKeywords(Command command, String commandStr) {
return command.keywords().stream().filter(keyword -> hasPotentialMatch(keyword, commandStr)).findAny()
.isPresent();
}
private static Optional<String> findApplianceName(String commandStr, List<String> applianceNames) {
return applianceNames.stream().filter(applianceName -> hasPotentialMatch(applianceName, commandStr))
.findFirst();
}
private static boolean hasPotentialMatch(String keyword, String commandStr) {
return commandStr.toLowerCase().indexOf(keyword.toLowerCase()) != -1;
}
}
This class receives the provided command string and perform keyword searching to identify the right command and appliance to perform the right action.
Code for HomeAutomation class:
xxxxxxxxxx
package org.trishinfotech.command;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.trishinfotech.command.commands.Commands.DecreaseSpeedCommand;
import org.trishinfotech.command.commands.Commands.IncreaseSpeedCommand;
import org.trishinfotech.command.commands.Commands.OffCommand;
import org.trishinfotech.command.commands.Commands.OnCommand;
import org.trishinfotech.command.commands.Commands.TVDecreaseChannelCommand;
import org.trishinfotech.command.commands.Commands.TVDecreaseVolumeCommand;
import org.trishinfotech.command.commands.Commands.TVIncreaseChannelCommand;
import org.trishinfotech.command.commands.Commands.TVIncreaseVolumeCommand;
import org.trishinfotech.command.commands.Commands.TVMuteCommand;
import org.trishinfotech.command.devices.Appliance;
import org.trishinfotech.command.devices.bedroom.BedRoomFan;
import org.trishinfotech.command.devices.bedroom.BedRoomLight;
import org.trishinfotech.command.devices.kitchen.KitchenLight;
import org.trishinfotech.command.devices.kitchen.Microwave;
import org.trishinfotech.command.devices.livingroom.LivingRoomFan;
import org.trishinfotech.command.devices.livingroom.LivingRoomLight;
import org.trishinfotech.command.devices.livingroom.LivingRoomTV;
public class HomeAutomation {
private Map<Appliance, List<Command>> optionsAvailable = new HashMap<Appliance, List<Command>>();
private HomeAutomation() {
Appliance bedRoomFan = new BedRoomFan();
Appliance bedRoomLight = new BedRoomLight();
Appliance kitchenLight = new KitchenLight();
Appliance microwave = new Microwave();
Appliance livingRoomFan = new LivingRoomFan();
Appliance livingRoomLight = new LivingRoomLight();
Appliance livingRoomTV = new LivingRoomTV();
optionsAvailable.put(bedRoomFan,
Arrays.asList(new OnCommand("BedRoomFan On", bedRoomFan), new OffCommand("BedRoomFan Off", bedRoomFan),
new IncreaseSpeedCommand("BedRoomFan Increase", bedRoomFan),
new DecreaseSpeedCommand("BedRoomFan Decrease", bedRoomFan)));
optionsAvailable.put(bedRoomLight, Arrays.asList(new OnCommand("BedRoomLight On", bedRoomLight),
new OffCommand("BedRoomLight On", bedRoomLight)));
optionsAvailable.put(kitchenLight, Arrays.asList(new OnCommand("KitchenLight On", kitchenLight),
new OffCommand("KitchenLight Off", kitchenLight)));
optionsAvailable.put(microwave,
Arrays.asList(new OnCommand("Microwave On", microwave), new OffCommand("Microwave Off", microwave)));
optionsAvailable.put(livingRoomFan,
Arrays.asList(new OnCommand("LivingRoomFan On", livingRoomFan),
new OffCommand("LivingRoomFan Off", livingRoomFan),
new IncreaseSpeedCommand("LivingRoomFan Increase", livingRoomFan),
new DecreaseSpeedCommand("LivingRoomFan Decrease", livingRoomFan)));
optionsAvailable.put(livingRoomLight, Arrays.asList(new OnCommand("LivingRoomLight On", livingRoomLight),
new OffCommand("LivingRoomLight Off", livingRoomLight)));
optionsAvailable.put(livingRoomTV,
Arrays.asList(new OnCommand("LivingRoomTV On", livingRoomTV),
new OffCommand("LivingRoomTV Off", livingRoomTV),
new TVIncreaseVolumeCommand("LivingRoomTV Increase Volume", livingRoomTV),
new TVIncreaseChannelCommand("LivingRoomTV Decrease Channel", livingRoomTV),
new TVDecreaseVolumeCommand("LivingRoomTV Decrease Volume", livingRoomTV),
new TVDecreaseChannelCommand("LivingRoomTV Decrease Channel", livingRoomTV),
new TVMuteCommand("LivingRoomTV Mute/Unmute", livingRoomTV)));
}
public List<String> applianceNames() {
return optionsAvailable.keySet().stream().map(appliance -> appliance.name()).collect(Collectors.toList());
}
public List<Command> applianceCommands(String applianceName) {
List<Command> commands = new ArrayList<Command>();
if (applianceName != null && !applianceName.trim().isEmpty()) {
Optional<Appliance> applianceSelected = optionsAvailable.keySet().stream()
.filter(appliance -> appliance.name().equalsIgnoreCase(applianceName.trim())).findAny();
if (applianceSelected.isPresent()) {
commands.addAll(optionsAvailable.get(applianceSelected.get()));
}
}
return commands;
}
public static HomeAutomation INSTANCE = new HomeAutomation();
}
I wrote this class as a Home Automation Hub (singleton). You can read more on in my article on Singleton Design Pattern.
Code for HomeRemote class:
xxxxxxxxxx
package org.trishinfotech.command;
public class HomeRemote {
Command command;
public HomeRemote() {
super();
}
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
System.out.println("---------------------------------------------------------------------------");
System.out.printf("Executing command '%s' on appliance '%s'...\n", command.name(), command.appliance().name());
command.execute();
System.out.println("Done!");
System.out.println("---------------------------------------------------------------------------");
System.out.println("\n");
}
}
This HomeRemote will act as Invoker for us.
Now it's time to write Main program to execute and test output.
xxxxxxxxxx
package org.trishinfotech.command;
import java.util.Optional;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String commandStr = null;
HomeRemote remote = new HomeRemote();
try (Scanner scanner = new Scanner(System.in)) {
do {
System.out.println("Please enter command to operate on your Home Appliances (Press Ctrl + C to end)");
System.out.println("-------------------------------------------------------------------------------");
System.out.printf(" Available Devices: %s\n", HomeAutomation.INSTANCE.applianceNames());
System.out.println("-------------------------------------------------------------------------------");
System.out.print("Alexa>");
commandStr = scanner.nextLine();
Optional<Command> commandOption = CommandInterpreter.interpretCommand(commandStr);
if (commandOption.isPresent()) {
Command command = commandOption.get();
remote.setCommand(command);
remote.pressButton();
} else {
System.out.println("Sorry! I am not sure how to do that? Please try again!\n");
}
} while(true);
}
}
}
Below is the command to run this code post mvn build.
xxxxxxxxxx
java -cp command.jar org.trishinfotech.command.Main
And here's the output:
java -cp command.jar org.trishinfotech.command.Main
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>turn on bedroomlight
---------------------------------------------------------------------------
Executing command 'BedRoomLight On' on appliance 'BedRoomLight'...
Turning On 'BedRoomLight'
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>swtch on livingroomtv
---------------------------------------------------------------------------
Executing command 'LivingRoomTV On' on appliance 'LivingRoomTV'...
Turning On 'LivingRoomTV'
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>decrease livingroomtv volume
---------------------------------------------------------------------------
Executing command 'LivingRoomTV Decrease Volume' on appliance 'LivingRoomTV'...
Decreasing volume of 'LivingRoomTV' to '0'.
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>livingroomtv decrease volume
---------------------------------------------------------------------------
Executing command 'LivingRoomTV Decrease Volume' on appliance 'LivingRoomTV'...
'LivingRoomTV' is already on mute!
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>increase volume livigroomtv
Sorry! I am not sure how to do that? Please try again!
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>increase volume livingroomtv
---------------------------------------------------------------------------
Executing command 'LivingRoomTV Increase Volume' on appliance 'LivingRoomTV'...
Encreasing volume of 'LivingRoomTV' to '1'.
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>increase channel livingroomtv
---------------------------------------------------------------------------
Executing command 'LivingRoomTV Decrease Channel' on appliance 'LivingRoomTV'...
Encreasing channel of 'LivingRoomTV' to '2'.
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>start bedroomfan
---------------------------------------------------------------------------
Executing command 'BedRoomFan On' on appliance 'BedRoomFan'...
Turning On 'BedRoomFan'
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>increase bedroomfan
---------------------------------------------------------------------------
Executing command 'BedRoomFan Increase' on appliance 'BedRoomFan'...
Encreasing Speed of 'BedRoomFan' to '2'.
Done!
---------------------------------------------------------------------------
Please enter command to operate on your Home Appliances (Press Ctrl + C to end)
-------------------------------------------------------------------------------
Available Devices: [BedRoomLight, KitchenLight, LivingRoomFan, BedRoomFan, LivingRoomTV, LivingRoomLight, Microwave]
-------------------------------------------------------------------------------
Alexa>
Looks good!
Source Code can be found here: Command-Design-Pattern-Sample-Code
I hope this tutorial demonstrates the use of command design pattern.
Liked the article? Please don't forget to press that like button. Happy coding!
Need more articles, please visit my profile: Brijesh Saxena.
Opinions expressed by DZone contributors are their own.
Comments