Implementing an observer pattern with events

I am working on a Silverlight application where I used excessive use of the observer pattern. In my implementation, I created two interfaces, IObservable<T> and IObserver<T> . The former contain methods for attaching and removing observers from observables. The latter has a Notify(IObservable<T> observable, ...) method Notify(IObservable<T> observable, ...) , which is called by the observable passing itself as a parameter through observer.Notify(this, ...) when the observable changed its state.

Now I came across "events", and for me it looks as if it were an implementation of the observer pattern, just with the delegates, and not with the above Notify method. Is it correct?

I don't know much about delegates and don’t want to spend hours rewriting my code to finish the code that does the same thing as it. Events, on the other hand, may differ from an observer pattern based on an interface. Did I miss something?

+3
source share
1 answer

Events are an implementation of the observer pattern.

An event is implemented as a list of methods that are called when a valve is raised.

Delegates are method references: unlike Java, C # offers a method reference method.

It’s not a priori better to use events than to implement an observer pattern. But events offer a fairly general way to do this, and in many cases are highly optimized for this task, thus providing a more efficient and convenient way to organize this.

The delegate is determined by the signature of the expected method. For instance:

 public delegate void FooMethod (Bar x, Baz y); 

You define a delegate for the void methods given Bar and a Baz . Therefore, if you have an instance of the following class:

 public class Qux { public void Method (Bar x, Baz y) { //do something return null; } } 

Then you can refer to the method:

 Qux q = new Qux(); FooMethod fm = q.Method; 

An event , therefore, is a delegate list with the same signature:

You define the event as:

 private event FooMethod SomeEvent; 

You can add delegate (listeners) using the += operator:

 SomeEvent += q.Method; 

remove the delegate with the -= operator and raise the event with:

 SomeEvent(new Bar(), new Baz()); 

It is as if you are calling one method that dispatches.

By calling event , all registered delegate will be called in the registration order.

Note : calling SomeEvent(new Bar(), new Baz()); , this does not mean that each delegate receives new instances: instances are first created and divided into all delegate calls.

Conclusion I think the C # developers did a great job with observer patterns, as the programmer is no longer responsible for the correct programming. In addition, events are easy to understand and use convenient syntax. In special situations, however, programmers may need to implement the observer himself. But these are very rare cases.

+6
source

Source: https://habr.com/ru/post/1244673/


All Articles