C++11實現觀察者模式

C++11中的std::function可以接受函數指針、std::bind、lambda表達式等函數,可以達到很鬆的耦合,簡直就是爲事件機制設計的。但是不能簡單判斷兩個std::function是不是同一函數,所以下面我用ID來標識listener

我模仿C#的委託實現了觀察者模式:

#pragma once
#include <functional>
#include <map>
#include <crtdbg.h>


template<class KeyCmp, class... ArgTypes>
class Event final
{
public:
    typedef std::function<void(ArgTypes...)> FunctionType;

private:
    class Listener
    {
    public:
        FunctionType m_function;
        // 這裏可以添加額外信息
    };

    std::map<int, Listener, KeyCmp> m_listeners;
    int m_nextListenerID = 0;


public:
    // 返回listener ID
    int AddListener(FunctionType callback)
    {
        int listenerID = m_nextListenerID++;
        Listener& listener = m_listeners[listenerID];
        listener.m_function = std::move(callback);
        return listenerID;
    }

    void DeleteListener(int listenerID)
    {
        m_listeners.erase(listenerID);
    }

    void operator () (ArgTypes... args)
    {
        for (auto it = m_listeners.cbegin(); it != m_listeners.cend(); ++it)
        {
            try
            {
                it->second.m_function(std::forward<ArgTypes>(args)...);
            }
            catch (std::bad_function_call&)
            {
                _RPTF0(_CRT_WARN, "回調事件時出現bad_function_call\n");
            }

            if (m_listeners._Isnil(it._Mynode()))
            {
                // 不能在回調時把這個listener刪了
                _RPTF0(_CRT_WARN, "迭代調用事件時當前結點被刪除\n");
                break;
            }
        }
    }
};

// 先監聽先被調用
template<class... ArgTypes>
using PreEvent = Event<std::less<int>, ArgTypes...>;

// 先監聽後被調用
template<class... ArgTypes>
using PostEvent = Event<std::greater<int>, ArgTypes...>;

使用方法:

PreEvent<int, const std::string&> g_someEvent;

int _tmain(int argc, _TCHAR* argv[])
{
    // 添加監聽器
    int id = g_someEvent.AddListener([](int arg1, const std::string& arg2){
        std::cout << "arg1 = " << arg1 << std::endl;
        std::cout << "arg2 = " << arg2 << std::endl;
    });

    // 觸發事件
    g_someEvent(123, "test");

    // 刪除監聽器
    g_someEvent.DeleteListener(id);

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章