
Registration
The second and third requirements can be achieved by offering some public methods that allow registration with the messaging system. If we force the listening object to provide us a delegate function to call when the message is broadcast, then this allows listeners to customize which method is called for which message. We can make our code base very easy to understand if we name the delegate after the message it is intended to process.
In some cases, we might wish to broadcast a general notification message and have all listeners do something in response, such as an Enemy Created message. Other times, we might be sending a message that specifically targets a single listener among a group. For example, we might want to send an Enemy Health Value Changed message that is intended for a specific health bar object that is attached to the enemy that was damaged. However, we may have many health bar objects in the scene, all of which are interested in this message type, but each is only interested in hearing health update messages for the enemy they're providing health information for. So, if we implement a way for the system to stop checking after it has been handled, then we can probably save a good number of CPU cycles when many listeners are waiting for the same message type.
The delegate we define should, therefore, provide a way to retrieve the message via an argument and return a response that determines whether or not processing for the message should stop if and when the listener is done with it. The decision on whether to stop processing or not can be achieved by returning a simple Boolean, where true implies that this listener has handled the message and the processing for the message must stop, and false implies that this listener has not handled the message and the messaging system should try the next listener.
Here is the definition for the delegate:
public delegate bool MessageHandlerDelegate(Message message);
Listeners must define a method of this form and pass a delegate reference to the messaging system during registration, hence providing a means for the messaging system to tell the listening object when the message is being broadcast.