Last active
February 2, 2024 03:21
-
-
Save silahian/32186509ec9e0461017d377db0faa48e to your computer and use it in GitHub Desktop.
Observer pattern created by silahian - https://repl.it/HpbL/15
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 <string> | |
#include <vector> | |
#include <thread> | |
#include <iostream> | |
#include <unistd.h> | |
using namespace std; | |
class IObserver | |
{ | |
public: | |
virtual void OnNotify() = 0; | |
}; | |
class Strategy : public IObserver | |
{ | |
public: | |
string StrategyName = ""; | |
int StrategyTimeout = 0; | |
virtual void OnNotify() | |
{ | |
sleep(StrategyTimeout); | |
std::cout << StrategyName << " has been notified." << std::endl; | |
} | |
}; | |
class ISubject | |
{ | |
public: | |
virtual bool RegisterObserver(IObserver* pObserver) = 0; | |
virtual void Notify() = 0; | |
}; | |
class OrderBook : public ISubject | |
{ | |
public: | |
OrderBook(): m_ObserverCount(0), m_pObservers() | |
{} | |
virtual bool RegisterObserver(IObserver* pObserver) | |
{ | |
m_pObservers[m_ObserverCount++] = pObserver; | |
return true; | |
} | |
virtual void Notify() | |
{ | |
//Send notification to all observers | |
for(int i = 0; i < m_ObserverCount; i++) | |
m_pObservers[i]->OnNotify(); | |
} | |
private: | |
static const int ObserverCountMax = 10; | |
IObserver* m_pObservers[ObserverCountMax]; | |
int m_ObserverCount; | |
}; | |
int main() | |
{ | |
OrderBook LOB; | |
Strategy strategies[10]; | |
int iCount = 1; | |
for(auto& s : strategies) | |
{ | |
s.StrategyName = "Strategy " + to_string(iCount++); | |
s.StrategyTimeout = 150; //let's assume that each strategy will take 150ms to process | |
LOB.RegisterObserver(&s); | |
} | |
LOB.Notify(); | |
return 0; | |
} | |
Each strategy should have a separated thread to not stop the notification for each one...
So when a strategy receives a new notification, is ready to start doing fancy calculations on his own thread...
and also i think is good idea to parallelize that notify fun.
great work! i love your content/code on github is very usefull!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work!
How about parallelizing the OrderBook::Notify() function?
would that make the pattern usable?