Observer 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
  2. *
  3. * This library is open source and may be redistributed and/or modified under
  4. * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
  5. * (at your option) any later version. The full license is in LICENSE file
  6. * included with this distribution, and on the openscenegraph.org website.
  7. *
  8. * This library is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * OpenSceneGraph Public License for more details.
  12. */
  13. #ifndef OSG_OBSERVER
  14. #define OSG_OBSERVER 1
  15. #include <OpenThreads/Mutex>
  16. #include <osg/Referenced>
  17. #include <set>
  18. namespace osg {
  19. /** Observer base class for tracking when objects are unreferenced (their reference count goes to 0) and are being deleted.*/
  20. class OSG_EXPORT Observer
  21. {
  22. public:
  23. Observer();
  24. virtual ~Observer();
  25. /** objectDeleted is called when the observed object is about to be deleted. The observer will be automatically
  26. * removed from the observed object's observer set so there is no need for the objectDeleted implementation
  27. * to call removeObserver() on the observed object. */
  28. virtual void objectDeleted(void*) {}
  29. };
  30. /** Class used by osg::Referenced to track the observers associated with it.*/
  31. class OSG_EXPORT ObserverSet : public osg::Referenced
  32. {
  33. public:
  34. ObserverSet(const Referenced* observedObject);
  35. Referenced* getObserverdObject() { return _observedObject; }
  36. const Referenced* getObserverdObject() const { return _observedObject; }
  37. /** "Lock" a Referenced object i.e., protect it from being deleted
  38. * by incrementing its reference count.
  39. *
  40. * returns null if object doesn't exist anymore. */
  41. Referenced* addRefLock();
  42. inline OpenThreads::Mutex* getObserverSetMutex() const { return &_mutex; }
  43. void addObserver(Observer* observer);
  44. void removeObserver(Observer* observer);
  45. void signalObjectDeleted(void* ptr);
  46. typedef std::set<Observer*> Observers;
  47. Observers& getObservers() { return _observers; }
  48. const Observers& getObservers() const { return _observers; }
  49. protected:
  50. ObserverSet(const ObserverSet& rhs): osg::Referenced(rhs) {}
  51. ObserverSet& operator = (const ObserverSet& /*rhs*/) { return *this; }
  52. virtual ~ObserverSet();
  53. mutable OpenThreads::Mutex _mutex;
  54. Referenced* _observedObject;
  55. Observers _observers;
  56. };
  57. }
  58. #endif