2009-08-08 10 views
114

Recentemente ho iniziato a scavare in C# ma non riesco a capire come funzionano i delegati quando si implementa lo schema osservatore/osservabile nella lingua.Esempio semplicissimo di osservatore C#/osservabile con i delegati

Qualcuno potrebbe darmi un esempio semplicissimo di come è fatto? I hanno googled questo, ma tutti gli esempi che ho trovato erano troppo problem-specifici o troppo "gonfiati".

risposta

188

Il modello di osservatore viene in genere implementato con events.

Ecco un esempio:

using System; 

class Observable 
{ 
    public event EventHandler SomethingHappened; 

    public void DoSomething() 
    { 
     EventHandler handler = SomethingHappened; 
     if (handler != null) 
     { 
      handler(this, EventArgs.Empty); 
     } 
    } 
} 

class Observer 
{ 
    public void HandleEvent(object sender, EventArgs args) 
    { 
     Console.WriteLine("Something happened to " + sender); 
    } 
} 

class Test 
{ 
    static void Main() 
    { 
     Observable observable = new Observable(); 
     Observer observer = new Observer(); 
     observable.SomethingHappened += observer.HandleEvent; 

     observable.DoSomething(); 
    } 
} 

vedere l'articolo collegato per molti più dettagli.

+15

Per risparmiare alcune righe ed evitare il controllo null, inizializza il tuo evento in questo modo: http://stackoverflow.com/questions/340610/create-empty-c-event-handlers-automatically/ 340618 # 340618 – Dinah

+1

@Dinah: Ciò non evita il controllo nullo. Puoi ancora impostare 'SomethingHappened = null' in un secondo momento (un metodo pratico, se pigro e non ideale, per annullare l'iscrizione di tutti i gestori), quindi il controllo null è sempre necessario. –

+3

@DanPuzey: Puoi farlo all'interno della classe, ma allo stesso tempo puoi assicurarti che * non lo faccia * e * l'altro * codice non possa farlo, in quanto può solo iscriversi e disiscriversi. Se ti assicuri che non lo imposti mai in modo deliberato all'interno della tua classe, va bene evitare il controllo nullo. –

16

Ecco un semplice esempio:

public class ObservableClass 
{ 
    private Int32 _Value; 

    public Int32 Value 
    { 
     get { return _Value; } 
     set 
     { 
      if (_Value != value) 
      { 
       _Value = value; 
       OnValueChanged(); 
      } 
     } 
    } 

    public event EventHandler ValueChanged; 

    protected void OnValueChanged() 
    { 
     if (ValueChanged != null) 
      ValueChanged(this, EventArgs.Empty); 
    } 
} 

public class ObserverClass 
{ 
    public ObserverClass(ObservableClass observable) 
    { 
     observable.ValueChanged += TheValueChanged; 
    } 

    private void TheValueChanged(Object sender, EventArgs e) 
    { 
     Console.Out.WriteLine("Value changed to " + 
      ((ObservableClass)sender).Value); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     ObservableClass observable = new ObservableClass(); 
     ObserverClass observer = new ObserverClass(observable); 
     observable.Value = 10; 
    } 
} 

Nota:

  • Questo viola una regola che io non sganciare l'osservatore della osservabile, questo è forse abbastanza buono per questo semplice esempio , ma assicurati di non tenere gli osservatori appesi ai tuoi eventi in quel modo. Un modo per gestire questo sarebbe rendere ObserverClass IDisposable e lasciare che il metodo .Dispose faccia l'opposto del codice nel costruttore
  • Nessun controllo degli errori eseguito, almeno un controllo Null dovrebbe essere fatto nel costruttore del ObserverClass
5

Controllare questa introduzione al quadro Rx che utilizza meraviglioso IObserver-IObservable non-blocking modello di programmazione asincrona introducing-rx-linq-to-events

+0

Una cosa bella se si utilizza Silverlight - purtroppo non è molto utile per il resto di noi. Una vergogna. –

+0

Puoi convertirlo in .net clr. Vedi qui http://evain.net/blog/articles/2009/07/30/rebasing-system-reactive-to-the-net-clr – Ray

+0

Anche questo farà parte di .NET 4.0 (e non solo per Silverlight) – Ray

5

ho legato insieme un paio di grandi esempi di cui sopra (grazie come sempre a Mr. Skeet e Mr. Karlsen) per includere un paio di osservabili diversi e utilizzato un'interfaccia per mantenere cremagliera di loro nel Observer e ha permesso l'osservatore a di "osservare" un qualsiasi numero di osservabili tramite un elenco interno:

namespace ObservablePattern 
{ 
    using System; 
    using System.Collections.Generic; 

    internal static class Program 
    { 
     private static void Main() 
     { 
      var observable = new Observable(); 
      var anotherObservable = new AnotherObservable(); 

      using (IObserver observer = new Observer(observable)) 
      { 
       observable.DoSomething(); 
       observer.Add(anotherObservable); 
       anotherObservable.DoSomething(); 
      } 

      Console.ReadLine(); 
     } 
    } 

    internal interface IObservable 
    { 
     event EventHandler SomethingHappened; 
    } 

    internal sealed class Observable : IObservable 
    { 
     public event EventHandler SomethingHappened; 

     public void DoSomething() 
     { 
      var handler = this.SomethingHappened; 

      Console.WriteLine("About to do something."); 
      if (handler != null) 
      { 
       handler(this, EventArgs.Empty); 
      } 
     } 
    } 

    internal sealed class AnotherObservable : IObservable 
    { 
     public event EventHandler SomethingHappened; 

     public void DoSomething() 
     { 
      var handler = this.SomethingHappened; 

      Console.WriteLine("About to do something different."); 
      if (handler != null) 
      { 
       handler(this, EventArgs.Empty); 
      } 
     } 
    } 

    internal interface IObserver : IDisposable 
    { 
     void Add(IObservable observable); 

     void Remove(IObservable observable); 
    } 

    internal sealed class Observer : IObserver 
    { 
     private readonly Lazy<IList<IObservable>> observables = 
      new Lazy<IList<IObservable>>(() => new List<IObservable>()); 

     public Observer() 
     { 
     } 

     public Observer(IObservable observable) : this() 
     { 
      this.Add(observable); 
     } 

     public void Add(IObservable observable) 
     { 
      if (observable == null) 
      { 
       return; 
      } 

      lock (this.observables) 
      { 
       this.observables.Value.Add(observable); 
       observable.SomethingHappened += HandleEvent; 
      } 
     } 

     public void Remove(IObservable observable) 
     { 
      if (observable == null) 
      { 
       return; 
      } 

      lock (this.observables) 
      { 
       observable.SomethingHappened -= HandleEvent; 
       this.observables.Value.Remove(observable); 
      } 
     } 

     public void Dispose() 
     { 
      for (var i = this.observables.Value.Count - 1; i >= 0; i--) 
      { 
       this.Remove(this.observables.Value[i]); 
      } 
     } 

     private static void HandleEvent(object sender, EventArgs args) 
     { 
      Console.WriteLine("Something happened to " + sender); 
     } 
    } 
} 
0

I did't voglio cambiare il mio codice sorgente per aggiungere ulteriori osservatore, così ho scritto seguente semplice esempio:

//EVENT DRIVEN OBSERVER PATTERN 
public class Publisher 
{ 
    public Publisher() 
    { 
     var observable = new Observable(); 
     observable.PublishData("Hello World!"); 
    } 
} 

//Server will send data to this class's PublishData method 
public class Observable 
{ 
    public event Receive OnReceive; 

    public void PublishData(string data) 
    { 
     //Add all the observer below 
     //1st observer 
     IObserver iObserver = new Observer1(); 
     this.OnReceive += iObserver.ReceiveData; 
     //2nd observer 
     IObserver iObserver2 = new Observer2(); 
     this.OnReceive += iObserver2.ReceiveData; 

     //publish data 
     var handler = OnReceive; 
     if (handler != null) 
     { 
      handler(data); 
     } 
    } 
} 

public interface IObserver 
{ 
    void ReceiveData(string data); 
} 

//Observer example 
public class Observer1 : IObserver 
{ 
    public void ReceiveData(string data) 
    { 
     //sample observers does nothing with data :) 
    } 
} 

public class Observer2 : IObserver 
{ 
    public void ReceiveData(string data) 
    { 
     //sample observers does nothing with data :) 
    } 
} 
1
/**********************Simple Example ***********************/  

class Program 
     { 
      static void Main(string[] args) 
      { 
       Parent p = new Parent(); 
      } 
     } 

     //////////////////////////////////////////// 

     public delegate void DelegateName(string data); 

     class Child 
     { 
      public event DelegateName delegateName; 

      public void call() 
      { 
       delegateName("Narottam"); 
      } 
     } 

     /////////////////////////////////////////// 

     class Parent 
     { 
      public Parent() 
      { 
       Child c = new Child(); 
       c.delegateName += new DelegateName(print); 
       //or like this 
       //c.delegateName += print; 
       c.call(); 
      } 

      public void print(string name) 
      { 
       Console.WriteLine("yes we got the name : " + name); 
      } 
     } 
0

Qualcosa di simile a questo:

// interface implementation publisher 
public delegate void eiSubjectEventHandler(eiSubject subject); 

public interface eiSubject 
{ 
    event eiSubjectEventHandler OnUpdate; 

    void GenereteEventUpdate(); 

} 

// class implementation publisher 
class ecSubject : eiSubject 
{ 
    private event eiSubjectEventHandler _OnUpdate = null; 
    public event eiSubjectEventHandler OnUpdate 
    { 
     add 
     { 
      lock (this) 
      { 
       _OnUpdate -= value; 
       _OnUpdate += value; 
      } 
     } 
     remove { lock (this) { _OnUpdate -= value; } } 
    } 

    public void GenereteEventUpdate() 
    { 
     eiSubjectEventHandler handler = _OnUpdate; 

     if (handler != null) 
     { 
      handler(this); 
     } 
    } 

} 

// interface implementation subscriber 
public interface eiObserver 
{ 
    void DoOnUpdate(eiSubject subject); 

} 

// class implementation subscriber 
class ecObserver : eiObserver 
{ 
    public virtual void DoOnUpdate(eiSubject subject) 
    { 
    } 
} 

. observer pattern C# with event . link to the repository

4

Applicando il modello Observer con i delegati e gli eventi in C# si chiama "Pattern Evento" secondo il MSDN che è una leggera variazione.

In questo articolo troverete esempi ben strutturati su come applicare il modello in C# sia nel modo classico sia utilizzando i delegati e gli eventi.

Exploring the Observer Design Pattern

public class Stock 
{ 

    //declare a delegate for the event 
    public delegate void AskPriceChangedHandler(object sender, 
      AskPriceChangedEventArgs e); 
    //declare the event using the delegate 
    public event AskPriceChangedHandler AskPriceChanged; 

    //instance variable for ask price 
    object _askPrice; 

    //property for ask price 
    public object AskPrice 
    { 

     set 
     { 
      //set the instance variable 
      _askPrice = value; 

      //fire the event 
      OnAskPriceChanged(); 
     } 

    }//AskPrice property 

    //method to fire event delegate with proper name 
    protected void OnAskPriceChanged() 
    { 

     AskPriceChanged(this, new AskPriceChangedEventArgs(_askPrice)); 

    }//AskPriceChanged 

}//Stock class 

//specialized event class for the askpricechanged event 
public class AskPriceChangedEventArgs : EventArgs 
{ 

    //instance variable to store the ask price 
    private object _askPrice; 

    //constructor that sets askprice 
    public AskPriceChangedEventArgs(object askPrice) { _askPrice = askPrice; } 

    //public property for the ask price 
    public object AskPrice { get { return _askPrice; } } 

}//AskPriceChangedEventArgs 
12

In questo modello, si hanno gli editori che farà un po 'di logica e pubblicare un "evento".
Gli editori invieranno il loro evento solo agli abbonati che si sono abbonati per ricevere l'evento specifico.

In C#, qualsiasi oggetto può pubblicare un set di eventi a cui altre applicazioni possono iscriversi.
Quando la classe di pubblicazione genera un evento, vengono notificate tutte le applicazioni sottoscritte.
La figura seguente mostra questo meccanismo.

enter image description here

più semplice esempio possibile in Eventi e delegati in C#:

codice si spiega da sé, inoltre ho aggiunto i commenti per cancellare il codice.

using System; 

public class Publisher //main publisher class which will invoke methods of all subscriber classes 
{ 
    public delegate void TickHandler(Publisher m, EventArgs e); //declaring a delegate 
    public TickHandler Tick;  //creating an object of delegate 
    public EventArgs e = null; //set 2nd paramter empty 
    public void Start()  //starting point of thread 
    { 
     while (true) 
     { 
      System.Threading.Thread.Sleep(300); 
      if (Tick != null) //check if delegate object points to any listener classes method 
      { 
       Tick(this, e); //if it points i.e. not null then invoke that method! 
      } 
     } 
    } 
} 

public class Subscriber1    //1st subscriber class 
{ 
    public void Subscribe(Publisher m) //get the object of pubisher class 
    { 
     m.Tick += HeardIt;    //attach listener class method to publisher class delegate object 
    } 
    private void HeardIt(Publisher m, EventArgs e) //subscriber class method 
    { 
     System.Console.WriteLine("Heard It by Listener"); 
    } 

} 
public class Subscriber2     //2nd subscriber class 
{ 
    public void Subscribe2(Publisher m) //get the object of pubisher class 
    { 
     m.Tick += HeardIt;    //attach listener class method to publisher class delegate object 
    } 
    private void HeardIt(Publisher m, EventArgs e) //subscriber class method 
    { 
     System.Console.WriteLine("Heard It by Listener2"); 
    } 

} 

class Test 
{ 
    static void Main() 
    { 
     Publisher m = new Publisher();  //create an object of publisher class which will later be passed on subscriber classes 
     Subscriber1 l = new Subscriber1(); //create object of 1st subscriber class 
     Subscriber2 l2 = new Subscriber2(); //create object of 2nd subscriber class 
     l.Subscribe(m);  //we pass object of publisher class to access delegate of publisher class 
     l2.Subscribe2(m); //we pass object of publisher class to access delegate of publisher class 

     m.Start();   //starting point of publisher class 
    } 
} 

uscita:

sentito da Listener

sentito da Listener2

sentito da Listener

E Sentito da Listener2

E ascoltati dal Ascolta er . . . (infinite volte)

+1

Questo è fantastico, grazie per l'esempio semplice e chiaro. –

+1

Hai salvato la mia giornata :) Grazie ... –