I was reading up on observer pattern to refactor codes in the Update(), which lead me to some write-up on event driven programming. For event driven programming, three key components were mentioned;
Event Listener - object that wants to be notified about an event when it happens.
Event Announcer - object that detect when the event occurs and announce it to all listeners to be notified.
Event Manager - Singleton object that accepts notifications of events and publish the notifications to all appropriate listeners.
So the tutorial went on with writing up the codes for the 3 components.
Question is why go through all these when we could have just use delegate event object and register to the delegate to be notified of the event? Net result seems to be the same (or not) ?
In the observable object, have the delegate declared and initialized:
public delegate void MyDelegate();
public class Target : MonoBehaviour
{
public event MyDelegate myDelegate;
}
// Run myDelegate when required.
}
The key reason here is to decouple the two parts of your code base.
Under a Broadcaster, Receiver system the Receiver must know about the Broadcaster.
Under the Broadcaster, Manager, Receiver system the Broadcaster and the Reciever do not know about each other. Instead they both know about the Manager. This can be really useful when you need to couple multiple disparate systems.
It might be easier to think in terms of multiplayer programming.
Suppose you’re playing a chess game with someone. When you touch a chess piece, it glows. Your opponent should also see your piece glow on their end as well.
So let’s break that down. What should happen when you touch a chess piece?
Your event creator tells the broadcaster that a chess piece has been touched (which one, and by whom).
You have listeners who tell the broadcaster, “Hey if TouchPieceAction happens, I want to know about it!”
One of those listeners is the network manager (or the broadcaster itself can be the network manager). The TouchPieceAction is packed into a network message to send to the opponent’s network manager.
The opponent’s broadcaster receives the TouchPieceAction from you, and broadcasts that to all its listeners.
One of those listeners is the glow shader thingamajig that activates around that specific chess piece using a specific color (along with maybe a name label) representing who touched it.
In the chess example above, the glow shader thingamajig only has one place to connect to so it doesn’t need to care about where the TouchPieceAction came from (either via input, UI, network, whatever).
The regular internet loves to talk about Design Patterns. “Observer Pattern vs. Event Driven” will probably get some fun hits.
But a manager in the middle is good for consumable events. Touches and clicks, say. Instead of sending the click out to everyone, a manager could ask them in turn until one wants it.