Created
February 1, 2019 16:31
-
-
Save mcspr/a627ea626775b5a6dcc6fb1aa8561979 to your computer and use it in GitHub Desktop.
Possible broker implementation
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 <functional> | |
#include <iostream> | |
#include <vector> | |
template <typename Event> | |
class Broker { | |
public: | |
virtual ~Broker() {} | |
using handler_t = std::function<void (const Broker<Event>& broker, const Event&)>; | |
private: | |
class Runner { | |
public: | |
virtual ~Runner() {} | |
void subscribe(handler_t handler) { | |
handlers.push_back(handler); | |
} | |
void publish(const Broker<Event>& broker, const Event& event) { | |
for (auto handler : handlers) { | |
handler(broker, event); | |
} | |
} | |
private: | |
std::vector<handler_t> handlers; | |
}; | |
static Runner& getInstance() { | |
static Runner runner; | |
return runner; | |
} | |
public: | |
void subscribe(handler_t handler) { | |
Broker<Event>::getInstance().subscribe(handler); | |
} | |
void publish(const Event& event) { | |
Broker<Event>::getInstance().publish(*this, event); | |
} | |
std::uintptr_t getId() const { | |
return reinterpret_cast<std::uintptr_t>(this); | |
} | |
}; | |
class SomeEvent {}; | |
class OtherEvent {}; | |
Broker<SomeEvent> broker_one; | |
Broker<SomeEvent> broker_two; | |
Broker<OtherEvent> broker_three; | |
template<typename A, typename B> | |
bool is_same(const A& one, const B& two) { | |
return (one.getId() == two.getId()); | |
} | |
void some_handler(const Broker<SomeEvent>& broker, const SomeEvent& event) { | |
std::cout << "received some_handler from "; | |
if (is_same(broker, broker_one)) | |
std::cout << "1" << std::endl; | |
if (is_same(broker, broker_two)) | |
std::cout << "2" << std::endl; | |
if (is_same(broker, broker_three)) | |
std::cout << "3" << std::endl; | |
std::cout << std::endl; | |
} | |
int main(int argc, char** argv) { | |
std::cout << "1 id: " << broker_one.getId() << std::endl; | |
std::cout << "2 id: " << broker_two.getId() << std::endl; | |
std::cout << "3 id: " << broker_three.getId() << std::endl; | |
std::cout << std::endl; | |
SomeEvent tmp_event; | |
broker_one.subscribe(some_handler); | |
std::cout << "publishing to 2" << std::endl; | |
broker_two.publish(tmp_event); | |
std::cout << "publishing to 1" << std::endl; | |
broker_one.publish(tmp_event); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment