| 1 | // |
|---|---|
| 2 | // NotificationCenter.cpp |
| 3 | // |
| 4 | // Library: Foundation |
| 5 | // Package: Notifications |
| 6 | // Module: NotificationCenter |
| 7 | // |
| 8 | // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. |
| 9 | // and Contributors. |
| 10 | // |
| 11 | // SPDX-License-Identifier: BSL-1.0 |
| 12 | // |
| 13 | |
| 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 | |
| 21 | |
| 22 | namespace Poco { |
| 23 | |
| 24 | |
| 25 | NotificationCenter::NotificationCenter() |
| 26 | { |
| 27 | } |
| 28 | |
| 29 | |
| 30 | NotificationCenter::~NotificationCenter() |
| 31 | { |
| 32 | } |
| 33 | |
| 34 | |
| 35 | void NotificationCenter::addObserver(const AbstractObserver& observer) |
| 36 | { |
| 37 | Mutex::ScopedLock lock(_mutex); |
| 38 | _observers.push_back(observer.clone()); |
| 39 | } |
| 40 | |
| 41 | |
| 42 | void NotificationCenter::removeObserver(const AbstractObserver& observer) |
| 43 | { |
| 44 | Mutex::ScopedLock lock(_mutex); |
| 45 | for (ObserverList::iterator it = _observers.begin(); it != _observers.end(); ++it) |
| 46 | { |
| 47 | if (observer.equals(**it)) |
| 48 | { |
| 49 | (*it)->disable(); |
| 50 | _observers.erase(it); |
| 51 | return; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | |
| 57 | bool NotificationCenter::hasObserver(const AbstractObserver& observer) const |
| 58 | { |
| 59 | Mutex::ScopedLock lock(_mutex); |
| 60 | for (ObserverList::const_iterator it = _observers.begin(); it != _observers.end(); ++it) |
| 61 | if (observer.equals(**it)) return true; |
| 62 | |
| 63 | return false; |
| 64 | } |
| 65 | |
| 66 | |
| 67 | void NotificationCenter::postNotification(Notification::Ptr pNotification) |
| 68 | { |
| 69 | poco_check_ptr (pNotification); |
| 70 | |
| 71 | ScopedLockWithUnlock<Mutex> lock(_mutex); |
| 72 | ObserverList observersToNotify(_observers); |
| 73 | lock.unlock(); |
| 74 | for (ObserverList::iterator it = observersToNotify.begin(); it != observersToNotify.end(); ++it) |
| 75 | { |
| 76 | (*it)->notify(pNotification); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | |
| 81 | bool NotificationCenter::hasObservers() const |
| 82 | { |
| 83 | Mutex::ScopedLock lock(_mutex); |
| 84 | |
| 85 | return !_observers.empty(); |
| 86 | } |
| 87 | |
| 88 | |
| 89 | std::size_t NotificationCenter::countObservers() const |
| 90 | { |
| 91 | Mutex::ScopedLock lock(_mutex); |
| 92 | |
| 93 | return _observers.size(); |
| 94 | } |
| 95 | |
| 96 | |
| 97 | namespace |
| 98 | { |
| 99 | static SingletonHolder<NotificationCenter> sh; |
| 100 | } |
| 101 | |
| 102 | |
| 103 | NotificationCenter& NotificationCenter::defaultCenter() |
| 104 | { |
| 105 | return *sh.get(); |
| 106 | } |
| 107 | |
| 108 | |
| 109 | } // namespace Poco |
| 110 |