OnJava8-Examples/patterns/CommandPattern.java

50 lines
974 B
Java
Raw Normal View History

2015-05-05 11:20:13 -07:00
//: patterns/CommandPattern.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-05-05 11:20:13 -07:00
import java.util.*;
interface Command {
void execute();
}
class Hello implements Command {
@Override
public void execute() {
System.out.print("Hello ");
}
}
class World implements Command {
@Override
public void execute() {
System.out.print("World! ");
}
}
class IAm implements Command {
@Override
public void execute() {
System.out.print("I'm the command pattern!");
}
}
// A Command object that holds commands:
class Macro implements Command {
2015-05-18 23:05:20 -07:00
private ArrayList<Command> commands =
2015-05-06 15:14:33 -07:00
new ArrayList<>();
2015-05-05 11:20:13 -07:00
public void add(Command c) { commands.add(c); }
@Override
public void execute() {
2015-05-27 23:30:19 -07:00
commands.forEach(Command::execute);
2015-05-05 11:20:13 -07:00
}
}
public class CommandPattern {
public static void main(String args[]) {
Macro macro = new Macro();
macro.add(new Hello());
macro.add(new World());
macro.add(new IAm());
macro.execute();
}
} ///:~