Skip to content

Instantly share code, notes, and snippets.

@tsu-nera
Created September 16, 2017 10:34
Show Gist options
  • Save tsu-nera/58d0365cedd0f55d3fe5df3159d6729b to your computer and use it in GitHub Desktop.
Save tsu-nera/58d0365cedd0f55d3fe5df3159d6729b to your computer and use it in GitHub Desktop.
Command Pattern with lambda
package gof.command;
import java.util.Stack;
class CommandSample3 {
////////////////////
// Command
////////////////////
abstract public static class Command {
public void setReceiver(Receiver receiver) {
}
public abstract void execute();
}
@FunctionalInterface
public interface Executor {
void run();
}
public static class Data1 extends Command {
protected Receiver receiver;
private String str1 = "Suzuki";
private String str2 = "Ichiro";
public void setReceiver(Receiver receiver) {
this.receiver = receiver;
}
public void execute() {
receiver.action( () -> System.out.println(str1 + " " + str2));
}
}
public static class Data2 extends Command {
protected Receiver receiver;
private String str = "Jonney";
public void setReceiver(Receiver receiver) {
this.receiver = receiver;
}
public void execute() {
receiver.action(() -> System.out.println(str));
}
}
////////////////////
// Receiver
////////////////////
public interface Receiver {
void action(Executor executor);
}
public static class NamePrinter implements Receiver {
public void action(Executor executor) {
executor.run();
}
}
////////////////////
// Invoker
////////////////////
public static class Invoker {
private Stack<Command> commands = new Stack<>();
public void addCommand(Command command) {
commands.push(command);
}
public void execute() {
for (Command command : commands) {
command.execute();
}
}
}
public static void main(String[] args) {
NamePrinter name = new NamePrinter();
Command data1, data2;
Invoker invoker = new Invoker();
data1 = new Data1();
data1.setReceiver(name);
data2 = new Data2();
data2.setReceiver(name);
invoker.addCommand(data1);
invoker.addCommand(data2);
invoker.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment