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 java.util.ArrayList;
19 import java.util.List;
21 import java.util.TreeMap;
24 * Implements subscription and notification logic for an observer pattern. This
25 * class is thread safe.
27 public class Observable<ObservableType, Event> {
31 private ObservableType observable;
34 * Used to notify observers.
36 private ObserverNotifier<ObservableType, Event> notifier;
39 * Map of subscription to observer.
41 private Map<Long, Observer<ObservableType, Event>> observers;
44 * Counter for subscriptions. Holds the next subscription.
49 * Constructs the observable.
52 * Observable this instance is used for.
54 * Object used for implementing notification of listeners.
56 public Observable(ObservableType aObservable,
57 ObserverNotifier<ObservableType, Event> aNotifier) {
58 observable = aObservable;
60 observers = new TreeMap<Long, Observer<ObservableType, Event>>();
65 * Subscribe an obvers.
68 * Observer to subscribe.
69 * @return Event Event to send.
71 public synchronized long subscribe(Observer<ObservableType, Event> aObserver) {
72 long subscription = counter++; // integer rage is so large it will
75 observers.put(subscription, aObserver);
81 * Unsubscribe an observer.
83 * @param aSubscription
84 * Subscription which is used
85 * @throws IllegalArgumentException
86 * In case the subscription is not known.
88 public synchronized void unsubscribe(long aSubscription) {
89 Object obj = observers.remove(aSubscription);
92 throw new IllegalArgumentException("Subscription '" +
98 * Gets the number of subscribed observers.
100 * @return Number of subscribed observers.
102 public int getObserverCount() {
103 return observers.size();
107 * Notifies all subscribed observers.
112 public void send(Event aEvent) {
113 // Make sure we do the notification while not holding the lock to avoid
114 // potential deadlock
116 List<Observer<ObservableType, Event>> myObservers = new ArrayList<Observer<ObservableType, Event>>();
118 synchronized (this) {
119 myObservers.addAll(observers.values());
122 for (Observer<ObservableType, Event> observer : myObservers) {
123 notifier.update(observer, observable, aEvent);