-
Notifications
You must be signed in to change notification settings - Fork 1
/
ObserverExerciseInstructorSolution.java
75 lines (64 loc) · 1.73 KB
/
ObserverExerciseInstructorSolution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package behavioral.observer.exerciseinstructorsolution;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
class Event<T>
{
private List<BiConsumer<Object, T>> consumers = new ArrayList<>();
public void subscribe(BiConsumer<Object, T> consumer)
{
consumers.add(consumer);
}
public void invoke(Object sender, T arg)
{
for (BiConsumer<Object, T> consumer : consumers)
consumer.accept(sender, arg);
}
}
class Game
{
public Event<Void> ratEnters = new Event<>();
public Event<Void> ratDies = new Event<>();
public Event<Rat> notifyRat = new Event<>();
}
class Rat implements Closeable
{
private Game game;
public int attack = 1;
public Rat(Game game)
{
this.game = game;
game.ratEnters.subscribe((sender, arg) -> {
if (sender != this)
{
++attack;
game.notifyRat.invoke(this, (Rat) sender);
}
});
game.notifyRat.subscribe((sender, rat) -> {
if (rat == this) ++attack;
});
game.ratDies.subscribe((sender, arg) -> --attack);
game.ratEnters.invoke(this, null);
}
@Override
public void close() throws IOException
{
// rat dies ;(
game.ratDies.invoke(this, null);
}
}
class ObserverExerciseSolutionDemo
{
public static void main(String[] args) throws IOException {
Game game = new Game();
Rat rat = new Rat(game);
Rat rat2 = new Rat(game);
Rat rat3 = new Rat(game);
System.out.println(rat.attack); // 3
rat3.close();
System.out.println(rat.attack); // 2
}
}