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: