Created
October 12, 2010 11:57
-
-
Save yuya-takeyama/622065 to your computer and use it in GitHub Desktop.
Observer Pattern implemented in C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
observer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <list> | |
using namespace std; | |
class Subject; | |
class Observer { | |
public: | |
virtual void update(Subject&) = 0; | |
}; | |
class Subject { | |
typedef std::list<Observer*>::iterator iterator; | |
private: | |
list<Observer*> observers; | |
string name; | |
public: | |
void add_observer(Observer&); | |
void notify(); | |
void set_name(string); | |
string get_name(); | |
}; | |
void Subject::add_observer(Observer& _observer) { | |
observers.push_back(&_observer); | |
} | |
void Subject::notify() { | |
for (iterator it = observers.begin(); it != observers.end(); it++) { | |
(*it)->update(*this); | |
} | |
} | |
void Subject::set_name(string s) { | |
name = s; | |
notify(); | |
} | |
string Subject::get_name() { | |
return name; | |
} | |
class NameObserver : public Observer { | |
public: | |
void update(Subject &s) { | |
cout << "Subject's name is changed as '" << s.get_name() << "'." << endl; | |
} | |
}; | |
class CountObserver : public Observer { | |
private: | |
int count; | |
public: | |
CountObserver() { | |
count = 0; | |
} | |
void update(Subject &s) { | |
count++; | |
cout << count << " times updated." << endl; | |
} | |
}; | |
int main() | |
{ | |
Subject subject; | |
subject.add_observer(*new NameObserver); | |
subject.add_observer(*new CountObserver); | |
subject.set_name("Yuya"); | |
subject.set_name("John"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very good example. Thanks!