Skip to content

Instantly share code, notes, and snippets.

@arttuladhar
Created July 14, 2018 04:10
Show Gist options
  • Save arttuladhar/30cf058fc767feb8ab9e0e8e0f17eafb to your computer and use it in GitHub Desktop.
Save arttuladhar/30cf058fc767feb8ab9e0e8e0f17eafb to your computer and use it in GitHub Desktop.
Command Design Pattern Example
package com.art.head_first.homeautomation;
public interface Command {
void execute();
void undo();
}
package com.art.head_first.homeautomation;
public class Light {
boolean isOn;
public void on(){
isOn = true;
System.out.println("Light is On");
}
public void off(){
isOn = false;
System.out.println("Light is Off");
}
}
package com.art.head_first.homeautomation;
public class LightOffCommand implements Command{
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
@Override
public void undo() {
light.on();
}
}
package com.art.head_first.homeautomation;
public class LightOnCommand implements Command{
Light light;
@Override
public void execute() {
light.on();
}
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void undo() {
light.off();
}
}
package com.art.head_first.homeautomation;
public class SimpleRemoteControl {
Command slot;
public void setCommand(Command command){
slot = command;
}
public void pressButton(){
slot.execute();
}
public void undo(){
slot.undo();
}
}
package com.art.head_first.homeautomation;
/**
* Client Class is responsible for Creating Concrete Commands and setting it's receiver
*/
public class SimpleRemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl rc = new SimpleRemoteControl();
Light light = new Light();
Stereo stereo = new Stereo();
rc.setCommand(new LightOnCommand(light));
rc.pressButton();
rc.undo();
rc.setCommand(new StereoOnCommand(stereo));
rc.pressButton();
rc.undo();
rc.setCommand(new StereoOffCommand(stereo));
rc.pressButton();
rc.undo();
}
}
package com.art.head_first.homeautomation;
public class Stereo {
boolean isOn;
int volume;
public void on(){
this.isOn = true;
System.out.println("Stereo is On");
}
public void off(){
this.isOn = false;
System.out.println("Stereo is Off");
}
public void setVolume(int volume)
{
this.volume = volume;
System.out.println("Stereo Volume is set to: " + volume);
}
}
package com.art.head_first.homeautomation;
public class StereoOffCommand implements Command{
Stereo stereo;
public StereoOffCommand(Stereo stereo) {
this.stereo = stereo;
}
@Override
public void execute() {
stereo.off();
}
@Override
public void undo() {
stereo.on();
}
}
package com.art.head_first.homeautomation;
public class StereoOnCommand implements Command{
Stereo stereo;
public StereoOnCommand(Stereo stereo) {
this.stereo = stereo;
}
@Override
public void execute() {
stereo.on();
}
@Override
public void undo() {
stereo.off();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment