3

Can someone please tell me the difference between these two different approaches. I know that both of them can handle the same scenario but is there any pros/cons of using the first or the second approach? What would you guys go for and why?

Direct subscription to the Event (using static Event) :

    public class MyEffect : BaseEffect
    {
      public delegate void EventHandler (Element sender, Unit target);
      public static event EventHandler OnMyEvent;

      public Damage(Element elementOwner)
      {
        this.Owner = elementOwner;
      }

      public void DispatchEvent(Unit target)
      {
        if (OnMyEvent != null)
        {
            OnMyEvent(this.Owner, target);
        }
      }
   }

=> Event Subscription :

      MyEffect.OnMyEvent += CallBack;

Or subscription via Singleton :

    public class MyEffect : BaseEffect
    {
      public delegate void EventHandler (Element sender, Unit target);
      public event EventHandler OnMyEvent;

      private static MyEffect instance;

      public static MyEffect Instance
      {
        get
        {
            return instance;
        }
      }

      public Damage(Element elementOwner)
      {
        this.Owner = elementOwner;
      }

      public void DispatchEvent(Unit target)
      {
        if (OnMyEvent != null)
        {
            OnMyEvent(this.Owner, target);
        }
      }
   }

=> Event Subscription :

      MyEffect.Instance.OnMyEvent += CallBack;
Bakkoto
  • 43
  • 4
  • Why does it have to be events? As far as I can tell, `event` is a bad model for your event. The .net key word `event` is for sub pub. – Aron Aug 18 '14 at 16:05
  • If this is your real implementation of singleton well it will return null. – terrybozzio Aug 18 '14 at 16:22
  • No ..it´s just an example...not my real implementation. – Bakkoto Aug 18 '14 at 17:09
  • @ARON sorry but i don´t get your point.Can you please explain in more details? – Bakkoto Aug 18 '14 at 17:23
  • @Wiktor Zychla why did you marked my quesion as duplicate? I´m not asking how or if i can or not ??I´m asking for the Pros/cons.By the way the user "Reed Copsey" in his answer to this : http://stackoverflow.com/questions/2789450/can-events-be-declared-as-static-if-yes-how-and-why said that using singleton is better.Correct me if I´m wrong. – Bakkoto Aug 18 '14 at 17:27
  • @Bakkoto: that is why I marked it as a duplicate. Reed's answer to the other question perfectly answers your question. – Wiktor Zychla Aug 18 '14 at 17:45

1 Answers1

1

Use the first approach. The object you have to instantiate is light-weight and unless you have an obvious reason to use the singleton (expensive object or heavily used et al.), adopt the simplest approach; which is the first of the above.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277