Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created May 12, 2017 07:42
Show Gist options
  • Save zhugw/36be2b4165f384affe46401fdde2ae76 to your computer and use it in GitHub Desktop.
Save zhugw/36be2b4165f384affe46401fdde2ae76 to your computer and use it in GitHub Desktop.
CommandPatternExample
// A Command Pattern example
// Oringinal example from https://dzone.com/articles/design-patterns-command and I modify it using java8
public class Client {
public static void main(String[] args) {
// Receiver
Light light = new Light();
// Invoker
RemoteControl remoteControl = new RemoteControl();
remoteControl.setCommand(light::switchOn);
remoteControl.pressButton();
System.out.println(light.isOn());
remoteControl.setCommand(light::switchOff);
remoteControl.pressButton();
System.out.println(light.isOn());
}
}
public interface Command {
void execute();
}
public class Light {
private boolean on;
public boolean isOn() {
return on;
}
public void switchOn(){
System.out.println("switchOn");
on = true;
}
public void switchOff(){
System.out.println("switchOff");
on = false;
}
}
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
void pressButton(){
command.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment