Skip to content

Commit 2a6b90f

Browse files
committed
functional interface cmd pattern
1 parent 61a6588 commit 2a6b90f

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package app.work;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.ArrayList;
5+
import java.util.Deque;
6+
import java.util.List;
7+
8+
public class CommandExecutor {
9+
List<ICommand> commands = new ArrayList<>();
10+
Deque<Runnable> undos = new ArrayDeque<>();
11+
12+
public void add(ICommand cmd) {
13+
this.commands.add(cmd);
14+
}
15+
16+
public boolean execute() {
17+
for (var cmd : commands) {
18+
try {
19+
var undo = cmd.execute();
20+
undos.push(undo);
21+
} catch(Exception e) {
22+
for (var undo : undos) {
23+
undo.run();
24+
}
25+
}
26+
}
27+
return true;
28+
}
29+
30+
interface ICommand {
31+
Runnable execute() throws Exception;
32+
}
33+
}

src/main/java/app/work/ICommand.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package app.work;
2+
3+
// public interface ICommand {
4+
// void execute();
5+
// }

src/main/java/app/work/Person.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package app.work;
2+
3+
import java.util.Optional;
4+
5+
import com.fasterxml.jackson.annotation.JsonInclude;
6+
7+
@JsonInclude(JsonInclude.Include.NON_EMPTY)
8+
public record Person(String name, int age, Optional<String> job) {
9+
public Person(String name, int age) {
10+
this(name, age, Optional.empty());
11+
}
12+
}

src/main/java/app/work/WorkController.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,28 @@ public String hello() {
8181
return "bar";
8282
}
8383

84+
@GetMapping("zach")
85+
public Person zach() {
86+
return new Person("zach", 31);
87+
}
88+
89+
@PostMapping("commands")
90+
public Person commands(@RequestBody Person person) {
91+
var executor = new CommandExecutor();
92+
var n = new Object() { int value = person.age(); };
93+
executor.add(() -> {
94+
var rand = ThreadLocalRandom.current().nextInt(5);
95+
if (rand < 3) {
96+
throw new Exception("Oops!");
97+
}
98+
n.value += rand;
99+
return () -> {
100+
};
101+
});
102+
executor.execute();
103+
return new Person(person.name(), n.value);
104+
}
105+
84106
@WithSpan
85107
private void doSomeWork(int time) throws InterruptedException {
86108
log.info("doing work for " + time + "ms");

0 commit comments

Comments
 (0)