The observer scheme works, but Observable object contains a list of all observers in heap, which is very inefficient.
class EXPORT Observable{
public:
typedef std::map<Observer*, int> ObserverList;
~Observable();
void addObserver(Observer *)const;
void removeObserver(Observer *)const;
void addWeakPtr(WeakPtrBase *)const;
void removeWeakPtr(WeakPtrBase *)const;
void notifyEvent(ObserveEvent &e)const;
protected:
mutable ObserverList observers;
};
This is because single observable can be observed by multiple observers like the figure below.
Note that actual implementation uses std::map, so each reference uses one memory block,
which means actual memory is even more fragmented than the figure.

However, if observer is observing single observable, the observer list can be made as a linked list
and observable can have a single pointer to traverse all the observers.

Each node (observer) will get one extra pointer larger size, but it will be far more efficient than dedicated memory block.
The problem is that Observer class is designed to support more than one observables at the same time.
You cannot use the pointer for two observers simultaneously.
If we use dynamically sized array or something, we would get back to original efficiency.
However, there's one variant of Observer that always has one reference to observable. That is WeakPtr. We can implement linked list for WeakPtr and keep observer list for other kinds of observers (maybe we should name them MultiObservers).
Having two implementations of observer management in one class is ugly, but we only add a single pointer to Observable and WeakPtrs. I think we can bear the cost.
The observer scheme works, but Observable object contains a list of all observers in heap, which is very inefficient.
This is because single observable can be observed by multiple observers like the figure below.
Note that actual implementation uses
std::map, so each reference uses one memory block,which means actual memory is even more fragmented than the figure.
However, if observer is observing single observable, the observer list can be made as a linked list
and observable can have a single pointer to traverse all the observers.
Each node (observer) will get one extra pointer larger size, but it will be far more efficient than dedicated memory block.
The problem is that Observer class is designed to support more than one observables at the same time.
You cannot use the pointer for two observers simultaneously.
If we use dynamically sized array or something, we would get back to original efficiency.
However, there's one variant of Observer that always has one reference to observable. That is WeakPtr. We can implement linked list for WeakPtr and keep observer list for other kinds of observers (maybe we should name them MultiObservers).
Having two implementations of observer management in one class is ugly, but we only add a single pointer to Observable and WeakPtrs. I think we can bear the cost.