1. import java.util.Collection;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import java.util.concurrent.atomic.AtomicReference;
  5. class CollectionObserver {
  6. // AtomicReference to hold the previous state of the collection
  7. private final AtomicReference<Collection<?>> previousCollection = new AtomicReference<>(null);
  8. // Callback interface for change notifications
  9. public interface ChangeListener {
  10. void onChange(Collection<?> collection);
  11. }
  12. // List to store listeners
  13. private final Set<ChangeListener> listeners = new HashSet<>();
  14. // Method to register a listener
  15. public void addListener(ChangeListener listener) {
  16. listeners.add(listener);
  17. }
  18. // Method to unregister a listener
  19. public void removeListener(ChangeListener listener) {
  20. listeners.remove(listener);
  21. }
  22. // Method to observe a collection
  23. public <T> void observe(Collection<T> collection) {
  24. if (previousCollection.get() == null) {
  25. // Initialize the previous state
  26. previousCollection.set(collection);
  27. notifyListeners(collection);
  28. return;
  29. }
  30. if (!collection.equals(previousCollection.get())) {
  31. // Collection has changed
  32. previousCollection.set(collection);
  33. notifyListeners(collection);
  34. }
  35. }
  36. // Method to notify listeners of a change
  37. private void notifyListeners(Collection<?> collection) {
  38. for (ChangeListener listener : listeners) {
  39. listener.onChange(collection);
  40. }
  41. }
  42. }

Add your comment