我策劃一個事件驅動的遊戲引擎。其基本思想是,不是讓所有事情都與一切事情交流,而是與事件系統進行交流,而不是將接收者與通知者或其他方式耦合起來。C++:事件系統實施一個遊戲引擎
- 對象登記自己的事件系統。通知ID和指向回調函數的指針作爲每個註冊命令的參數傳遞。
- 對象將通知添加到事件系統。通知的ID作爲每個通知的參數傳遞。通知被添加到保存所有待處理通知的隊列中。
- 此外,事件系統支持預定的通知。通知ID和將來的執行時間作爲每個通知的參數傳遞。然後按照未來的執行時間將預定通知存儲在保存預定通知的數據結構(「時間表」)中。
- 一個調用對象命令事件系統來處理所有排隊的通知。事件系統按順序提取通知,並調用每個已註冊自己的對象的回調函數,並使用與當前通知相同的ID。
- 調用者對象命令事件系統處理一個預定的通知。最早的通知是從計劃中提取的,並且調用了使用相同通知ID註冊的所有對象的回調。
。
class Registration
{
public:
void callback(void){ callback_(); }
void setCallback((*callback)(void));
void addToEventSystem(int ID, EventSystem &eventSystem);
private:
void (*callback_)(void);
};
class EventSystem
{
public:
void register(int ID, Registration* registration);
void unRegister(int ID, Registration* registration);
void addNotificationToQueue(int ID);
void addNotificationToSchedule(int ID, int notificationTime);
void processQueuedNotifications(void);
void processNextScheduled(void);
int getCurrentTime(void);
private:
//placeholder types
<list> notificationQueue;
<binaryheap> notificationSchedule;
};
//------------Use:------------------
class ReceiverObject
{
public:
void doStuff(void);
void initialize(void){
keyPressRegistration.setCallback(doStuff);
//multiple registrations with different ID:s to same eventsystem possible
keyPressRegistration.addToEventSystem(1234,eventSystem);
keyPressRegistration.addToEventSystem(42,eventSystem);};
private:
Registration keyPressRegistration;
};
int main()
{
ReceiverObject receiverObject;
EventSystem eventSystem;
receiverObject.initialize();
eventSystem.addNotificationToQueue(1234);
eventSystem.processQueuedNotifications();
}
但是我並不完全滿意這種解決方案,主要是因爲系統不允許容易傳遞參數給收件人,我懷疑回調成員函數,它是設計好做法?那麼我提出的方法/類/變量名稱呢?歡迎對這個問題提出建設性的批評,指導和替代方法。
如何爲您的回調傳遞'std :: function'而不是普通函數指針? –
確實那些看起來很有前途。我只是沒有經驗,也沒有關於C++ 11的知識,但是我會給新標準一個看看 – jms