In this lecture we will learn about the Command design pattern.
Watch the video within interaction mode which is only visible when you are logged in.
//Invoker
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
//Command Interface
public interface Command {
public void execute();
}
//Concrete Command
public class LightOffCommand implements Command {
// reference to the light
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.switchOff();
System.out.println("Light is off");
}
}
//Concrete Command
public class LightOnCommand implements Command {
// reference to the light
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.switchOn();
System.out.println("Light is on");
}
}
//Receiver
public class Light {
private boolean isOn;
public void switchOn() {
isOn = true;
}
public void switchOff() {
isOn = false;
}
}
public class Demo {
public static void main(String[] args) {
RemoteControl control = new RemoteControl();
Light light = new Light();
Command lightsOn = new LightOnCommand(light);
Command lightsOff = new LightOffCommand(light);
// switch on
control.setCommand(lightsOn);
control.pressButton();
// switch off
control.setCommand(lightsOff);
control.pressButton();
}
}
For example 1
To earn PASS status, system is about to evaluate you using multiple choice questions (MCQs) and True/False type questions.