I'm designing a library that will be used to intercept and process incoming messages from a message queue. Library users will write their own message handling functions for different kin开发者_Python百科ds of messages received.
I have a MessageConsumer
class that needs to handle messages of different kinds. I combined all handler functions into an abstract base class called MessageHandlerBase
. Library users will inherit from this and write their own MessageHandler
classes.
Relevant parts of the MessageConsumer
definition:
class MessageConsumer {
protected:
const MessageHandlerBase* m_mesgHandler;
public:
MessageConsumer( const std::string& brokerURI,
const std::string& inputQueueName,
const MessageHandlerBase* messageHandler);
virtual ~MessageConsumer() { this->cleanup(); }
void runConsumer();
virtual void onMessage( const Message& message )
{
// code to receive and parse messages ...
if ( message is of type 1 ) {
m_mesgHandler->handle_message_type_1(message);
else if ( message is of type 2 ) {
m_mesgHandler->handle_message_type_2(message);
// ... and so on for different types of messages
}
};
And the MessageHandlerBase
definition is
class MessageHandlerBase {
public:
virtual void handle_message_type_1( const Message& ) const =0;
virtual void handle_message_type_2( const Message& ) const =0;
virtual void handle_cms_exception() const {}
virtual void handle_transfer_interrupted() const {}
virtual void handle_transfer_resumed() const {}
};
Users usually will just care about handling messages of type 1 & 2 so I just made those pure virtual.
My big problem is this: While implementing their own MessageHandler
class's handle_message_type_1
and handle_message_type_2
methods, users need access to methods from one (or possibly more) of their helper classes. How can these classes be made available to MessageHandler
, without making them global? I can pass the class as a void*
argument to handle_message_type_1
but I don't want to because (i) what if I need to pass more than one functions and (ii) then I need to change the call in MessageConsumer
; I want to totally abstract these message handling details from MessageConsumer
.
Is there a more elegant way of handling this whole thing?
How can these classes be made available to
MessageHandler
, without making them global?
Users need to derive from your class. What stops them putting all kinds of data members into their derivate, referencing whatever they need?
That's the main advantage of using functors instead of function pointers: It makes void* userData
obsolete.
精彩评论