Re: Observer Design Pattern



On 31 May 2006 04:00:00 -0700, Krivenok Dmitry wrote:

Consider the following pseudo-code example:

class Subject
{
public:
virtual void Attach(Observer*) = 0;
virtual void Detach(Observer*) = 0;
virtual void Notify() = 0;

virtual @@@ GetState() = 0; // !!! What type should be returned???

Why there should be GetState at all? Isn't Subject's value a state of?

[and why people stick to pointers?]

};

class Observer
{
public:
virtual void Update(Subject*) = 0;
};

[...]
Main question:
How to avoid type switching in ConcreteObserver::Update(Subject* s)?

Avoid observers dependent on subjects. You had a concrete subject at hand
when you issued Notify() on it. Anything subject-specific should have been
done at that point. For an observer to do it, would be too late. One needed
multiple dispatch for that, but C++ does not have it, so your problem
actually is a manual emulation of.

If you want bidirectional exchange of messages between subjects and
observer, don't mix them with Notify. Do something like:

class Subject // Abstract
{
public:
virtual void Attach (Observer&) = 0;
virtual void Detach (Observer&) = 0;
virtual void Notify () = 0;

// Public actions on subjects
virtual void Jump () = 0;
virtual void Draw () = 0;
virtual void Plunk () = 0;
};

void MyObserver::Update (Subject& What)
{
What.Draw (); // Tell back to subject
What.Jump ();
What.Plunk ();
}

--
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de
.