I have a system, that receives messages (data chunks with a type) from somewhere (in this case network). Those are stored in a queue once received. Then these messages should get dispatched to handler functions and this got to happen fast (lots of messages)
Currently the system is designed in a way, that each Message type is an own class and overwrites a virtual function run(Handler&) which basicly calls the correct method in the handler. E.g.:
class PingMessage: public Message{
... // Some member variables
void run(Handler& handler){
handler.handlePing(*this);
}
}
class Handler{
void handlePing(const PingMessage& msg){...}
}
In this design, the Queue deletes the message, after it got dispatched. The problem is: Some handler functions need to store the message to execute them at a later time. Copying the message is not only a waste of memory and time (it gets deleted right after dispatch) but also not possible sometimes (complex deserialized data structures) So best would be to pass the ownership over to the handler.
I have the feeling, there is a design pattern or best practice for this. But I can't find it.
What I could imaging is calling a generic handler function "handleMessage(Type, Message*)" that switches on the type and does a dispatch with the Message static_cast'ed to the right type. Then it is clear by the convention of passing a pointer, that the handler is responsible for deleting the message. Maybe even use a base class, that does the switch and implements all handler functions empty. If a handler functions returns true, the handleMessage function deletes the Message, otherwise it assumes, the callee stored it somewhere. But I'm not sure if this is the right approach or if it incurs to much overhead. There seems to be to much room for errors.
Aucun commentaire:
Enregistrer un commentaire