Modern alternative to publisher subscriber pattern

会有一股神秘感。 提交于 2019-12-06 01:56:12

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!