I'm implementing an Observer pattern in C++. The observer objects need to access to member variables of the Observed class when they are notified. By now I've solved this thing adding a reference to the Observed class as a member variable of the Observer as follows:
class Observer{
public:
Observer(const Observable& obs) : observed_(obs){}
void notify(const Event& event){
// get Observable member and do stuff
}
private:
const Observable& observed_;
}
class Observable{
public:
void notify(const Event& event){
//observer list.notify
}
}
Is the reference a good way for this pattern or is better to use other strategies?
I'd recommend in this case having the Observable instance sent as a member of Event, this way an Observer can watch more than one object, and you also achieve loose coupling between the two classes.