C++ Observer

Da Andreabont's Wiki.

Codice

#include <iostream>
#include <list>
#include <string>

using namespace std;

/* PROTOTIPO SUBJECT */
class Subject;

/* OBSERVER (Interfaccia) */
class Observer {

public:
    virtual void Update(Subject* theChangedSubject) = 0;
   
};

/* SUBJECT */
class Subject {

public:
    void Attach(Observer* _obj) {
      _observers.push_back(_obj);
    }

    void Detach(Observer* _obj) {
      _observers.remove(_obj);
    }

    void Notify() {
      for(auto it: _observers) {
	it->Update(this);
      }
    }

private:
    list<Observer*> _observers;

};

/* IMPLEMENTO OBSERVER */
class RealObserver : public Observer {
  
public:
    RealObserver(Subject* s, string nome) {
      _name = nome;
      _subject = s;
      _subject->Attach(this);
    }
    
    ~RealObserver() {
      _subject->Detach(this);
    }
    
    void Update(Subject*) {
      cout << _name << ": Ricevuto Update dal Subject" << endl;
    }
    
    string getName() {
      return _name;
    }
    
private:
    Subject* _subject;
    string _name;
  
};

Esempio d'uso

/* MAIN */

int main() {
  
  Subject* sub = new Subject();
  sub->Notify();
  
  cout << "Creo Osservatore 1" << endl;
  
  RealObserver* obs1 = new RealObserver(sub, "Osservatore 1");
  sub->Notify();
  
  cout << "Creo Osservatore 2" << endl;
  
  RealObserver* obs2 = new RealObserver(sub, "Osservatore 2");
  sub->Notify();
  
}