Skip to content

Instantly share code, notes, and snippets.

@tapeshmittal
Forked from silahian/ObserverPattern.cpp
Created June 3, 2019 21:46
Show Gist options
  • Save tapeshmittal/d72e357ce36b7d9d60824f918fcf1510 to your computer and use it in GitHub Desktop.
Save tapeshmittal/d72e357ce36b7d9d60824f918fcf1510 to your computer and use it in GitHub Desktop.
Observer pattern created by silahian - https://repl.it/HpbL/15
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment