aboutsummaryrefslogtreecommitdiff
path: root/src/main/model/GroupObserver.java
diff options
context:
space:
mode:
authorYuuta Liang <yuutaw@student.cs.ubc.ca>2023-11-23 08:09:01 +0800
committerYuuta Liang <yuutaw@student.cs.ubc.ca>2023-11-23 08:09:01 +0800
commit65ea6c17a0c1348aa9ef4e158102ddf173936882 (patch)
tree7615366f76b6c94f46d8039aa20091f9ccd5609a /src/main/model/GroupObserver.java
parentb94b18c133f06cb176d8aa8bb40a8e24918d9ed6 (diff)
downloadjca-65ea6c17a0c1348aa9ef4e158102ddf173936882.tar
jca-65ea6c17a0c1348aa9ef4e158102ddf173936882.tar.gz
jca-65ea6c17a0c1348aa9ef4e158102ddf173936882.tar.bz2
jca-65ea6c17a0c1348aa9ef4e158102ddf173936882.zip
Add GUI
Signed-off-by: Yuuta Liang <yuutaw@student.cs.ubc.ca>
Diffstat (limited to 'src/main/model/GroupObserver.java')
-rw-r--r--src/main/model/GroupObserver.java48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/main/model/GroupObserver.java b/src/main/model/GroupObserver.java
new file mode 100644
index 0000000..41a9aac
--- /dev/null
+++ b/src/main/model/GroupObserver.java
@@ -0,0 +1,48 @@
+package model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A group of observers with different types registered.
+ */
+public class GroupObserver implements Observer {
+ /**
+ * The map. Because Java doesn't have dependent maps, they are left here as unchecked.
+ */
+ private final Map<Class, Observer> map = new HashMap<>();
+
+ /**
+ * EFFECTS: Register a data type with an observer. Override existing registrations with the same type.
+ * REQUIRES: cls != null, obs != null.
+ */
+ public <T> void register(Class<T> cls, Observer<T> obs) {
+ map.put(cls, obs);
+ }
+
+ /**
+ * EFFECTS: Notify the registered observer based on the type of 'o' with given arguments.
+ * Does nothing if no registration found. Subclasses are supported as long as a parent class observer is registered.
+ * Specific type match takes priority. Non-specific type match is not guaranteed to be the closest.
+ * REQUIRES: o != null, direction be DIRECTION_*, index >= 0 or == INDEX_NOT_IN_LIST.
+ */
+ @Override
+ public void accept(Object o, int direction, int i) {
+ Observer obs = map.get(o.getClass());
+ if (obs == null) {
+ Class supertype = map.keySet().stream().filter(clz -> clz.isInstance(o)).findFirst().orElse(null);
+ if (supertype == null) {
+ return;
+ }
+ obs = map.get(supertype);
+ }
+ obs.accept(o, direction, i);
+ }
+
+ /**
+ * EFFECTS: Count the observers.
+ */
+ public int getRegisteredObserverCount() {
+ return map.size();
+ }
+}