Medical Imaging Interaction Toolkit  2016.11.0
Medical Imaging Interaction Toolkit
berryListenerList.h
Go to the documentation of this file.
1 /*===================================================================
2 
3 BlueBerry Platform
4 
5 Copyright (c) German Cancer Research Center,
6 Division of Medical and Biological Informatics.
7 All rights reserved.
8 
9 This software is distributed WITHOUT ANY WARRANTY; without
10 even the implied warranty of MERCHANTABILITY or FITNESS FOR
11 A PARTICULAR PURPOSE.
12 
13 See LICENSE.txt or http://www.mitk.org for details.
14 
15 ===================================================================*/
16 
17 #ifndef BERRYLISTENERLIST_H
18 #define BERRYLISTENERLIST_H
19 
20 #include <QMutex>
21 #include <QList>
22 #include <QReadWriteLock>
23 
24 namespace berry {
25 
27 {
28  template<class T>
29  bool operator()(const T& l1, const T& l2) const
30  {
31  return l1 == l2;
32  }
33 };
34 
62 template<class T, typename C = ListenerListEquals>
64 {
65 
66 public:
67 
74  void Add(const T& listener)
75  {
76  // This method is synchronized to protect against multiple threads adding
77  // or removing listeners concurrently.
78 
79  // check for duplicates
80  QWriteLocker l(&mutex);
81  const int oldSize = listeners.size();
82  for (int i = 0; i < oldSize; ++i)
83  {
84  T& listener2 = listeners[i];
85  if (comparator(listener, listener2))
86  return;
87  }
88 
89  listeners.push_back(listener);
90  }
91 
104  QList<T> GetListeners() const
105  {
106  QReadLocker l(&mutex);
107  return listeners;
108  }
109 
116  bool IsEmpty() const
117  {
118  QReadLocker l(&mutex);
119  return listeners.empty();
120  }
121 
128  void Remove(const T &listener)
129  {
130  QWriteLocker l(&mutex);
131  // This method is synchronized to protect against multiple threads adding
132  // or removing listeners concurrently.
133  const int oldSize = listeners.size();
134  for (int i = 0; i < oldSize; ++i)
135  {
136  T& listener2 = listeners[i];
137  if (comparator(listener, listener2))
138  {
139  listeners.removeAt(i);
140  return;
141  }
142  }
143  }
144 
150  int Size() const
151  {
152  QReadLocker l(&mutex);
153  return listeners.size();
154  }
155 
159  void Clear()
160  {
161  QWriteLocker l(&mutex);
162  listeners.clear();
163  }
164 
165 private:
166 
170  QList<T> listeners;
171 
172  mutable QReadWriteLock mutex;
173 
174  C comparator;
175 };
176 
177 }
178 
179 #endif // BERRYLISTENERLIST_H
QList< T > GetListeners() const
bool operator()(const T &l1, const T &l2) const
void Add(const T &listener)
void Remove(const T &listener)