Although I’ve already said this elsewhere, as it is so very useful, I’m saving the snippets for these here, possibly again. As it is more about the pattern than the code, I’ll just give the pictures, and not the text. In fact I realise the SetValue and GetValue should have been moved into the base class. Never mind, another time.
I still find it all quite unintuitive…accepting that by its nature the Publisher/Subscriber pattern is not designed with intuition uppermost in one’s mind.
I deal in pictures, so to give some concrete expression to this, I thought of a few things that would maintain a movie in my head of the events and handlers playing out.
- SuperMario falling off a wall – where the random arguments from the event of hitting the ground dictate what type of ground he falls on – if concrete then he dies, if a mattress, OK etc
- Sniper randomly firing at people at specific coordinates. If the random ballistic coordinates matches a person’s position, then… you get the picture. Nah, not my style.
- A simple ball game, where similarly to the previous one, a person at specific coordinates does or does not catch the random ball throw. We’ll go with that, but for this phase, all we will do is tell the subscriber that the ball has been thrown… and then that the game has ended.
It is a console application, it has a Program.cs (subscriber) which instantiates the BallGame and its events (publisher). Although its useful to see examples of the Delegate keywords in practice, to understand how we get from that to [event] and EventHandler… I’m not going to do that.
So we have the BallGame class, with some messages to emphasise that it is the Publisher:
There is the EventArgs class, as the preferred way of passing event data around…
And lastly the client code:
The execution of the program: