Last active
December 15, 2017 22:53
-
-
Save prince-chrismc/39f30bf011da74b5a7b87c4fec4cc589 to your computer and use it in GitHub Desktop.
Quick and easy observer+decorator design pattern example base around printing a clock
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
class ISubject; | |
class IObserver | |
{ | |
protected: | |
ISubject* m_Subject; | |
public: | |
IObserver(ISubject* sub) : m_Subject(sub) {} | |
virtual void Update() = 0; | |
}; | |
class ISubject | |
{ | |
private: | |
std::vector<IObserver*> m_Observers; | |
public: | |
ISubject() : m_Observers() {} | |
void RegistarObserver(IObserver* obv) { m_Observers.emplace_back(obv); } | |
virtual void Notify() { for each(IObserver* obv in m_Observers) { if (obv == nullptr) continue; obv->Update(); } } | |
}; | |
class Clock : public ISubject | |
{ | |
public: | |
void Tick() { /*time++*/ Notify(); } | |
int GetSec(); | |
int GetMin(); | |
int GetHr(); | |
}; | |
class ClockWatcher : public IObserver | |
{ | |
public: | |
virtual void Update() { std::cout << m_Subject.GetSec(); } | |
int GetSec(); | |
int GetMin(); | |
int GetHr(); | |
}; | |
class ClockWatcherDecorator abstract : public ClockWatcher | |
{ | |
protected: | |
ClockWatcher* m_Clock; | |
public: | |
ClockWatcherDecorator(ClockWatcher* sub) : m_Clock(sub) {} | |
virtual void Update() = 0; | |
}; | |
class MinuteWatcher : public ClockWatcherDecorator | |
{ | |
virtual void Update() { std::cout << m_Subject.GetMin(); m_Clock.Update(); } | |
} | |
class HourWatcher : public ClockWatcherDecorator | |
{ | |
virtual void Update() { std::cout << m_Subject.GetHr(); m_Clock.Update(); } | |
} | |
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 "Decorated-Observer.h" | |
int main() | |
{ | |
Clock clock; | |
HourWatcher watch(&MinuteWatcher(&ClockWater(&clock))); | |
clock.RegistarObserver(&watch); | |
for(int i = 0; i < 10; i += 1) | |
clock.Tick(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment