import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
class CollectionObserver {
// AtomicReference to hold the previous state of the collection
private final AtomicReference<Collection<?>> previousCollection = new AtomicReference<>(null);
// Callback interface for change notifications
public interface ChangeListener {
void onChange(Collection<?> collection);
}
// List to store listeners
private final Set<ChangeListener> listeners = new HashSet<>();
// Method to register a listener
public void addListener(ChangeListener listener) {
listeners.add(listener);
}
// Method to unregister a listener
public void removeListener(ChangeListener listener) {
listeners.remove(listener);
}
// Method to observe a collection
public <T> void observe(Collection<T> collection) {
if (previousCollection.get() == null) {
// Initialize the previous state
previousCollection.set(collection);
notifyListeners(collection);
return;
}
if (!collection.equals(previousCollection.get())) {
// Collection has changed
previousCollection.set(collection);
notifyListeners(collection);
}
}
// Method to notify listeners of a change
private void notifyListeners(Collection<?> collection) {
for (ChangeListener listener : listeners) {
listener.onChange(collection);
}
}
}
Add your comment