2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.observer;
18 import org.apache.log4j.Logger;
20 import java.util.ArrayList;
21 import java.util.List;
23 import java.util.TreeMap;
26 * Implements subscription and notification logic for an observer pattern. This
27 * class is thread safe.
29 public class Observable<ObservableType, Event> {
30 private static final Logger LOGGER = Logger.getLogger(Observable.class);
35 private ObservableType observable;
38 * Used to notify observers.
40 private ObserverNotifier<ObservableType, Event> notifier;
43 * Map of subscription to observer.
45 private Map<Long, Observer<ObservableType, Event>> observers;
48 * Counter for subscriptions. Holds the next subscription.
53 * Constructs the observable.
56 * Observable this instance is used for.
58 * Object used for implementing notification of listeners.
60 public Observable(ObservableType aObservable,
61 ObserverNotifier<ObservableType, Event> aNotifier) {
62 observable = aObservable;
64 observers = new TreeMap<Long, Observer<ObservableType, Event>>();
69 * Subscribe an obvers.
72 * Observer to subscribe.
73 * @return Event Event to send.
75 public synchronized long subscribe(Observer<ObservableType, Event> aObserver) {
76 long subscription = counter++; // integer rage is so large it will
79 observers.put(subscription, aObserver);
85 * Unsubscribe an observer.
87 * @param aSubscription
88 * Subscription which is used
89 * @throws IllegalArgumentException
90 * In case the subscription is not known.
92 public synchronized void unsubscribe(long aSubscription) {
93 Object obj = observers.remove(aSubscription);
96 throw new IllegalArgumentException("Subscription '" +
102 * Gets the number of subscribed observers.
104 * @return Number of subscribed observers.
106 public int getObserverCount() {
107 return observers.size();
111 * Notifies all subscribed observers.
116 public void send(Event aEvent) {
117 // Make sure we do the notification while not holding the lock to avoid
118 // potential deadlock
120 List<Observer<ObservableType, Event>> myObservers = new ArrayList<Observer<ObservableType, Event>>();
122 synchronized (this) {
123 myObservers.addAll(observers.values());
126 for (Observer<ObservableType, Event> observer : myObservers) {
127 notifier.update(observer, observable, aEvent);