Created
September 16, 2017 10:34
-
-
Save tsu-nera/58d0365cedd0f55d3fe5df3159d6729b to your computer and use it in GitHub Desktop.
Command Pattern with lambda
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
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