File tree Expand file tree Collapse file tree 2 files changed +64
-1
lines changed Expand file tree Collapse file tree 2 files changed +64
-1
lines changed Original file line number Diff line number Diff line change 1+ package behavioral .observer ;
2+
3+ import java .io .Closeable ;
4+ import java .io .IOException ;
5+ import java .util .HashSet ;
6+ import java .util .Set ;
7+
8+ /*
9+ Game needs to propagate the change of the total number of rats to each rats
10+ Game is Observable/Publisher
11+ */
12+ class Game {
13+
14+ Set <Rat > rats = new HashSet <>(); // observers
15+
16+ void addRat (Rat rat ) {
17+ rats .add (rat );
18+ updateRatAttack ();
19+ }
20+
21+ void removeRat (Rat rat ) {
22+ rats .remove (rat );
23+ updateRatAttack ();
24+ }
25+
26+ void updateRatAttack () {
27+ rats .forEach (
28+ rat -> rat .attack = rats .size ()
29+ );
30+ System .out .println ("update each rat's attack as " + rats .size ());
31+ }
32+ }
33+
34+ class Rat implements Closeable // subscription
35+ {
36+
37+ private final Game game ;
38+ public int attack = 1 ; // keep the total number of rats
39+
40+ public Rat (Game game ) {
41+ this .game = game ;
42+ game .addRat (this ); // request
43+ }
44+
45+ @ Override
46+ public void close () {
47+ this .game .removeRat (this ); //cancel
48+ }
49+ }
50+
51+ public class Exercise {
52+
53+ public static void main (String [] args ) {
54+
55+ var game = new Game ();
56+
57+ var r1 = new Rat (game );
58+ var r2 = new Rat (game );
59+ var r3 = new Rat (game );
60+
61+ r1 .close ();
62+ }
63+ }
Original file line number Diff line number Diff line change @@ -29,7 +29,7 @@ private static void testObserver(RunnableObservable runnableObservable) {
2929 Observer ob1 = (o , arg ) -> System .out .println (Thread .currentThread ().getName () + " ob1 consume " + arg ); // override `void update` method
3030 Observer ob2 = (o , arg ) -> System .out .println (Thread .currentThread ().getName () + " ob2 consume " + arg );
3131
32- runnableObservable .addObserver (ob1 );
32+ runnableObservable .addObserver (ob1 ); // subscribe
3333 runnableObservable .addObserver (ob2 );
3434
3535 ExecutorService executorService = Executors .newSingleThreadExecutor ();
You can’t perform that action at this time.
0 commit comments