'Modern alternative to publisher subscriber pattern
I have a C++ Windows application. I am dealing with a publisher-subscriber situation, where one of my classes (publisher) generates data periodically and hands it off to another class (subscriber) which is constantly waiting to receive notification from the publisher. I am new to design patterns, and I looked up common implementations for publisher subscriber models, I noticed they are usually quite old, and they usually involve maintaining lists of pointers to objects. I was wondering if there is a better way of coding publisher subscriber model using C++ 11. Or using an entirely different model altogether in place of publisher - subscriber. If you can name some interesting features or approaches, I will read documentation for them, write an implementation and add it here for further review.
Update : I said I would post sample code. First, Boost Signals 2 as recommended by Jens really works great. My code is not quite different from the beginner sections on http://www.boost.org/doc/libs/1_55_0/doc/html/signals2/tutorial.html
Solution 1:[1]
You can store a vector of functions, here's a quick and dirty way:
template<class T>
class dispatcher
{
std::vector<std::function<void(T)> > functions;
public:
void subscribe(std::function<void(T)> f)
{
functions.push_back(f);
}
void publish(T x)
{
for(auto f:functions) f(x);
}
};
This doesn't have an unsubscribe(you would have to use a map for that).
However, this isn't thread-safe. If you want thread safety, you should you Boost.Signals2.
Solution 2:[2]
Well, if you want modern, really modern alternative, maybe, besides Boost.Signals2, as mentioned by Jens, you could try functional reactive programming paradigm.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | tonylo |
