Created
January 19, 2017 00:30
-
-
Save johnmarinelli/765cc376abdfa7fc2bf6dfb8289fc1d9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <vector> | |
class Subject; | |
class Observer | |
{ | |
public: | |
Observer(); | |
virtual void update(int subjVal) = 0; | |
virtual ~Observer(); | |
}; | |
Observer::Observer() | |
{ | |
} | |
Observer::~Observer() | |
{ | |
} | |
class Subject | |
{ | |
public: | |
Subject(); | |
void attach(Observer* obs); | |
void setValue(int value); | |
void notify(); | |
private: | |
int mValue; | |
std::vector<Observer*> mObservers; | |
}; | |
Subject::Subject() : | |
mValue(0), | |
mObservers() | |
{ | |
} | |
void Subject::attach(Observer* obs) | |
{ | |
mObservers.push_back(obs); | |
} | |
void Subject::notify() | |
{ | |
std::for_each(mObservers.begin(), | |
mObservers.end(), | |
[this] (Observer* obs) { | |
obs->update(this->mValue); | |
} | |
); | |
} | |
void Subject::setValue(int val) | |
{ | |
mValue = val; | |
notify(); | |
} | |
class DivObserver : public Observer | |
{ | |
public: | |
DivObserver(Subject* model, int div); | |
virtual void update(int subjVal); | |
~DivObserver(); | |
private: | |
int mDiv; | |
}; | |
DivObserver::DivObserver(Subject* model, int div) : | |
mDiv(div) | |
{ | |
model->attach(this); | |
} | |
void DivObserver::update(int subjVal) | |
{ | |
auto res = (subjVal / (double) mDiv); | |
std::cout << "DivObserver::update => " << res << '\n'; | |
} | |
DivObserver::~DivObserver() | |
{ | |
} | |
class ModObserver : public Observer | |
{ | |
public: | |
ModObserver(Subject* model, int mod); | |
virtual void update(int subjVal); | |
~ModObserver(); | |
private: | |
int mMod; | |
}; | |
ModObserver::ModObserver(Subject* model, int mod) : | |
mMod(mod) | |
{ | |
model->attach(this); | |
} | |
void ModObserver::update(int subjVal) | |
{ | |
auto res = (subjVal % mMod); | |
std::cout << "ModObserver::update => " << res << '\n'; | |
} | |
ModObserver::~ModObserver() | |
{ | |
} | |
int main(int argc, char* args[]) | |
{ | |
Subject subj; | |
DivObserver divo(&subj, 4); | |
ModObserver modo(&subj, 3); | |
subj.setValue(14); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment