Modern alternative to publisher subscriber pattern

10,028

Solution 1

Take a look at a signal library, e.g. Boost.Signals2 or libsigc++. They provide an abstraction to define a signal in your class to which clients can connect. All the logic to store connections etc is implemented there.

Solution 2

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 3

Well, if you want modern, really modern alternative, maybe, besides Boost.Signals2, as mentioned by Jens, you could try functional reactive programming paradigm.

Share:
10,028
The Vivandiere
Author by

The Vivandiere

Updated on June 04, 2022

Comments

  • The Vivandiere
    The Vivandiere almost 2 years

    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

  • The Vivandiere
    The Vivandiere over 9 years
    Interesting. I'll take a look, and write a basic code, thanks for the suggestion.