Created
May 12, 2017 07:42
-
-
Save zhugw/36be2b4165f384affe46401fdde2ae76 to your computer and use it in GitHub Desktop.
CommandPatternExample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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