c++ event監(jiān)聽(tīng)多事件技巧

c++
小樊
115
2024-07-24 14:33:15

在C++中監(jiān)聽(tīng)多個(gè)事件可以使用回調(diào)函數(shù)或者觀察者模式來(lái)實(shí)現(xiàn)。以下是一些技巧:

  1. 使用回調(diào)函數(shù):可以定義多個(gè)回調(diào)函數(shù),每個(gè)回調(diào)函數(shù)對(duì)應(yīng)一個(gè)事件。當(dāng)事件發(fā)生時(shí),調(diào)用相應(yīng)的回調(diào)函數(shù)來(lái)處理事件。這種方法簡(jiǎn)單直接,但可能會(huì)導(dǎo)致代碼混亂,難以維護(hù)。
#include <iostream>
#include <functional>

class EventListener {
public:
    void registerCallback(std::function<void()> callback) {
        callbacks.push_back(callback);
    }

    void fireEvent() {
        for (auto& callback : callbacks) {
            callback();
        }
    }

private:
    std::vector<std::function<void()>> callbacks;
};

int main() {
    EventListener listener;

    listener.registerCallback([]() {
        std::cout << "Event 1 occurred" << std::endl;
    });

    listener.registerCallback([]() {
        std::cout << "Event 2 occurred" << std::endl;
    });

    listener.fireEvent();

    return 0;
}
  1. 使用觀察者模式:定義一個(gè)Subject(主題)類和多個(gè)Observer(觀察者)類,Subject類維護(hù)一個(gè)Observer列表,當(dāng)事件發(fā)生時(shí)通知所有觀察者。這種方法將事件處理邏輯與事件監(jiān)聽(tīng)邏輯分離,使代碼更清晰。
#include <iostream>
#include <vector>

class Observer {
public:
    virtual void onEvent() = 0;
};

class Subject {
public:
    void addObserver(Observer* observer) {
        observers.push_back(observer);
    }

    void fireEvent() {
        for (auto& observer : observers) {
            observer->onEvent();
        }
    }

private:
    std::vector<Observer*> observers;
};

class Event1Observer : public Observer {
public:
    void onEvent() override {
        std::cout << "Event 1 occurred" << std::endl;
    }
};

class Event2Observer : public Observer {
public:
    void onEvent() override {
        std::cout << "Event 2 occurred" << std::endl;
    }
};

int main() {
    Subject subject;
    Event1Observer event1Observer;
    Event2Observer event2Observer;

    subject.addObserver(&event1Observer);
    subject.addObserver(&event2Observer);

    subject.fireEvent();

    return 0;
}

通過(guò)以上兩種方法,可以實(shí)現(xiàn)在C++中監(jiān)聽(tīng)多個(gè)事件的功能??梢愿鶕?jù)具體情況選擇適合的方法來(lái)實(shí)現(xiàn)。

0