mercredi 18 novembre 2020

Can I say that the relation between events and delegates adopts composite pattern?

An event can contain many handlers which are defined using delegate, my current understanding is that delegate is just an abstraction of function pointer. Since an event, which associated with a delegate type, can add / remove many delegates into it, and composite pattern treats a composite object the same as the terminal object, so the idea is:

composite.onTriggered();
// Internally:
// foreach(handler in composite)
// {
//     handler.onTriggered();
// }

will in turn call every handlers managed by the composite.

But it seems like public event EventHandler ThresholdReached does not define a composite, see my comment in the code below

class Counter
{
    public event EventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        EventHandler handler = ThresholdReached; // So what's the point of this line?
        handler?.Invoke(this, e);
        // Why not just:
     // ThresholdReached?.Invoke(this, e);
    } 

    // provide remaining implementation for the class
}

Am I correct about the idea in abstract level? If not could you provide any correction(s)?

Aucun commentaire:

Enregistrer un commentaire