Implementing the Observer Pattern via Delegates

What is the Observer Pattern ?

Make use of the Observer Pattern in situations where
1. You have an object -> Object A
2. Object A has 1 or more dependent objects -> Object A, Object B and Object C
3. When Object A’s state changes, Object B, C and D must be notified updated automatically

We have the class: TrainSignal
It contains a single delegate of type Action -> TrainIsComing
We know that the Action delegate takes no parameters and returns a void
It also contains the method HereComesTheTrain() -> which invokes the delegate
We also know that when a delegate is invoked, all the methods in the delegate’s invocation list are executed
So, the statement TrainIsComing(); = TrainIsComing.Invoke();
If the invocation list of TrainIsComing contains for example 2 methods, they will both be called
TrainSignal is our Object A

ObserverPatternViaDelegatesA.jpg
Next we have the Car class
The Car class needs to know if a train is coming
If a train is coming it will stop, obviously
We can say that the Car is interested in the state of TrainSignal or it’s an Observer
Car is dependent on TrainSignal -> Car is Object B, Object C, Object D
How does it work ?
The ctor for Car takes an instance of TrainSignal
Car then says to TrainSignal -> tell me when a train is coming so I can stop.
The Car does not want to get hit by the train.

observerpatternviadelegatesb

 

Let’s put it together
We create an instance of TrainSignal signal -> Object A
We create 3 Car instances Car 1, Car 2, Car 3 -> Object B, Object C, Object D
In the ctor for Car, each Car says to TrainSignal -> tell me when a train is coming
How do they do that ?
signal.TrainIsComing += Stop;
This statement adds the Car object and method Stop to TrainSignal’s invocation list
Remember that the delegate’s invocation list is just a collection of methods to call when the delegate is invoked
A train is coming so the TrainSignal instance invokes it’s delegate via a call to the method HereComesTheTrain()
When the delegate is invoked, each method in it’s invocation list is executed
The invocation list for signal is
1. c1.Stop();
2. c2.Stop();
3. c3.Stop();

The statement signal.HereComesTheTrain() executes the Stop method on c1, c2, c3 as you can see from the console output

ObserverPatternViaDelegatesC.jpg

observerpatternviadelegates1

Posted in Uncategorized

Leave a comment

Design a site like this with WordPress.com
Get started