From 65ea6c17a0c1348aa9ef4e158102ddf173936882 Mon Sep 17 00:00:00 2001 From: Yuuta Liang Date: Thu, 23 Nov 2023 08:09:01 +0800 Subject: Add GUI Signed-off-by: Yuuta Liang --- src/main/model/GroupObserver.java | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/model/GroupObserver.java (limited to 'src/main/model/GroupObserver.java') 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 map = new HashMap<>(); + + /** + * EFFECTS: Register a data type with an observer. Override existing registrations with the same type. + * REQUIRES: cls != null, obs != null. + */ + public void register(Class cls, Observer 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(); + } +} -- cgit v1.2.3