0

In observer pattern, subject notices a change to observer. But I also need subject to be notified by observer.

I went something like this for the purpose:

//Observer.h
class Subject;
class Observer{
public:
    void update(Subject* p_subject);
    void Subject_Notify();
private:
    Subject* subject;
}

//Subject.h
#include "Observer.h"
class Subject{
public:
    void observer_notify()
    {
        observer->update(this);
    }
    void update(Observer* observer);
private:
    Observer* observer;
}

//Observer.cpp
#include "Observer.h"
#include "Subject.h"
void Observer::update(Subject* p_subject)
{
    //do something with p_subject
}

void Observer::Subject_Notify()
{
    subject->update(this);
}

The code seems complicated and I am not sure if I am going in the right direction. Is there alternative or is this just ok?

Kevin
  • 1
  • 1
  • This looks more like a job for http://codereview.stackexchange.com/. What is the goal? Implementing the observer pattern or solving a real problem? The problem you are trying to solve can probably be solved easier and better without the observer pattern. – nwp Mar 08 '17 at 08:01
  • Observer pattern decouples your hard-coded relation, by allowing registration. And yes one observer can also be observed by other class including the observable. – Jarod42 Mar 08 '17 at 18:57
  • @nwp Yes, it's a real problem. – Kevin Mar 09 '17 at 01:21
  • @Jarod42 Thanks for comment. – Kevin Mar 09 '17 at 01:22
  • So you are asking *"how do I implement the observer pattern well"* and people might answer you, but the answer will be useless because while it does implement the pattern well it doesn't solve your actual problem. Instead you should ask how to solve your real problem and say that you tried using the pattern. See [XY-problem](https://meta.stackexchange.com/a/66378/266536). – nwp Mar 09 '17 at 07:28
  • It would be better if it was implemented with interfaces, and technically it should have a container in the subject to register the observers. Then, of course, it only makes sense to have an iterator. Just some thoughts. – Abstraction is everything. Mar 09 '17 at 08:03

0 Answers0