openscenegraph
Observer
Go to the documentation of this file.
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
14#ifndef OSG_OBSERVER
15#define OSG_OBSERVER 1
16
17#include <OpenThreads/Mutex>
18#include <osg/Referenced>
19#include <set>
20
21namespace osg {
22
23/** Observer base class for tracking when objects are unreferenced (their reference count goes to 0) and are being deleted.*/
24class OSG_EXPORT Observer
25{
26 public:
27 Observer();
28 virtual ~Observer();
29
30 /** objectDeleted is called when the observed object is about to be deleted. The observer will be automatically
31 * removed from the observed object's observer set so there is no need for the objectDeleted implementation
32 * to call removeObserver() on the observed object. */
33 virtual void objectDeleted(void*) {}
34
35};
36
37/** Class used by osg::Referenced to track the observers associated with it.*/
38class OSG_EXPORT ObserverSet : public osg::Referenced
39{
40 public:
41
42 ObserverSet(const Referenced* observedObject);
43
44 Referenced* getObserverdObject() { return _observedObject; }
45 const Referenced* getObserverdObject() const { return _observedObject; }
46
47 /** "Lock" a Referenced object i.e., protect it from being deleted
48 * by incrementing its reference count.
49 *
50 * returns null if object doesn't exist anymore. */
51 Referenced* addRefLock();
52
53 inline OpenThreads::Mutex* getObserverSetMutex() const { return &_mutex; }
54
55 void addObserver(Observer* observer);
56 void removeObserver(Observer* observer);
57
58 void signalObjectDeleted(void* ptr);
59
60 typedef std::set<Observer*> Observers;
61 Observers& getObservers() { return _observers; }
62 const Observers& getObservers() const { return _observers; }
63
64 protected:
65
66 ObserverSet(const ObserverSet& rhs): osg::Referenced(rhs) {}
67 ObserverSet& operator = (const ObserverSet& /*rhs*/) { return *this; }
68 virtual ~ObserverSet();
69
70 mutable OpenThreads::Mutex _mutex;
71 Referenced* _observedObject;
72 Observers _observers;
73};
74
75}
76
77#endif