NotificationCenter.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. //
  2. // NotificationCenter.cpp
  3. //
  4. // $Id: //poco/1.4/Foundation/src/NotificationCenter.cpp#2 $
  5. //
  6. // Library: Foundation
  7. // Package: Notifications
  8. // Module: NotificationCenter
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #include "Poco/NotificationCenter.h"
  16. #include "Poco/Notification.h"
  17. #include "Poco/Observer.h"
  18. #include "Poco/AutoPtr.h"
  19. #include "Poco/SingletonHolder.h"
  20. namespace Poco {
  21. NotificationCenter::NotificationCenter()
  22. {
  23. }
  24. NotificationCenter::~NotificationCenter()
  25. {
  26. }
  27. void NotificationCenter::addObserver(const AbstractObserver& observer)
  28. {
  29. Mutex::ScopedLock lock(_mutex);
  30. _observers.push_back(observer.clone());
  31. }
  32. void NotificationCenter::removeObserver(const AbstractObserver& observer)
  33. {
  34. Mutex::ScopedLock lock(_mutex);
  35. for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it)
  36. {
  37. if (observer.equals(**it))
  38. {
  39. (*it)->disable();
  40. _observers.erase(it);
  41. return;
  42. }
  43. }
  44. }
  45. bool NotificationCenter::hasObserver(const AbstractObserver& observer) const
  46. {
  47. Mutex::ScopedLock lock(_mutex);
  48. for (ObserverList::const_iterator it = _observers.begin(); it != _observers.end(); ++it)
  49. if (observer.equals(**it)) return true;
  50. return false;
  51. }
  52. void NotificationCenter::postNotification(Notification::Ptr pNotification)
  53. {
  54. poco_check_ptr (pNotification);
  55. ScopedLockWithUnlock<Mutex> lock(_mutex);
  56. ObserverList observersToNotify(_observers);
  57. lock.unlock();
  58. for (ObserverList::iterator it = observersToNotify.begin(); it != observersToNotify.end(); ++it)
  59. {
  60. (*it)->notify(pNotification);
  61. }
  62. }
  63. bool NotificationCenter::hasObservers() const
  64. {
  65. Mutex::ScopedLock lock(_mutex);
  66. return !_observers.empty();
  67. }
  68. std::size_t NotificationCenter::countObservers() const
  69. {
  70. Mutex::ScopedLock lock(_mutex);
  71. return _observers.size();
  72. }
  73. namespace
  74. {
  75. static SingletonHolder<NotificationCenter> sh;
  76. }
  77. NotificationCenter& NotificationCenter::defaultCenter()
  78. {
  79. return *sh.get();
  80. }
  81. } // namespace Poco