-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContainer.java
46 lines (37 loc) · 1.19 KB
/
Container.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
package com.soygul.capacitor;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Container for an immutable state object.
*/
public abstract class Container<T> {
private final List<Subscriber<T>> subscribers = new CopyOnWriteArrayList<>();
private T state;
public Container(T initialState) {
state = initialState;
}
public synchronized void setState(T state) {
if (this.state == state) {
throw new IllegalArgumentException("you need to provide a new copy of the immutable state object to set a new state");
}
if (this.state.equals(state)) {
throw new IllegalArgumentException("old and the new state are the same");
}
this.state = state;
for (Subscriber<T> s : subscribers) {
s.onStateChange(state);
}
}
public synchronized T getState() {
return state;
}
public synchronized void subscribe(Subscriber<T> s) {
subscribers.add(s);
}
public synchronized void unsubscribe(Subscriber<T> s) {
subscribers.remove(s);
}
public synchronized boolean haveSubscribers() {
return !subscribers.isEmpty();
}
}