forked from line/line-bot-sdk-java
-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathSubject.java
More file actions
60 lines (47 loc) · 1.35 KB
/
Subject.java
File metadata and controls
60 lines (47 loc) · 1.35 KB
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
package solution;
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers;
private String message;
private boolean changed;
public Subject() {
observers = new ArrayList<Observer>();
message = null;
changed = false;
}
public void register(Observer obj) {
if ( !observers.contains(obj) ) observers.add(obj);
}
public void unregister(Observer obj) {
observers.remove(obj);
}
public void notifyObservers() {
// if nothing is changed, we can skip this
if ( !changed ) return;
// we need to use a new list because observers may unsubscribe from the list
// and this might cause unexpected behaviours
// forEach is a faster way to loop over a list (see Java 1.8 lambda expression)
new ArrayList<>(observers).forEach( o -> o.update() );
// another approach to do it is to traverse the list starting from the end
for ( int i = observers.size()-1; i >= 0; --i ) {
observers.get(i).update();
}
// reset parameter
changed = false;
}
public void setMessage(String msg) {
this.message=msg;
this.changed=true;
notifyObservers();
}
public String getMessage() {
return message;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
public List<Observer> getQueue() {
return observers;
}
}