Observer Pattern C#

Contents

What is Observer Pattern?

Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

In this pattern, there are many observers (objects) that are observing a particular subject (also an object). Observers want to be notified when there is a change made inside the subject. So, they register themselves for that subject. When they lose interest in the subject, they simply unregister from the subject.

Observer Pattern Example

Let’s start with the problem statement,

The below code is a stock simulator that contains a list of dummy stock data. Each stock contains a name and price that we can monitor.

Now you don’t have to know the code for the stock simulator, it’s only going to be here to prove a point.

 1 using System;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 
 5 class Program
 6 {
 7     static void Main(string[] args)
 8     {
 9         
10         var stockSimulator = new StockSimulator();
11         foreach (var stock in stockSimulator)
12         {
13             //The below code that checks for Microsoft stock and 
14             //displays its changed price
15             if (stock.Name == "Microsoft")
16                 Console.WriteLine($"Microsoft new price is {stock.Price}");
17 
18             //The below code looks for google stock and check if 
19             //its reached the target price and display the price 
20             //when it reaches the target price.
21             if (stock.Name == "Google" && stock.Price > 50)
22                 Console.WriteLine($"Google reached target price {stock.Price}");
23         }
24         Console.ReadLine();
25     }
26 
27     public class StockSimulator : IEnumerable<Stock>
28     {
29         Random random;
30         string[] names = new string[3] { "Microsoft", "Google", "Apple" };
31 
32         public StockSimulator()
33         {
34             random = new Random(1024);
35         }
36 
37         public IEnumerator<Stock> GetEnumerator()
38         {
39             for (int i = 0; i < 20; i++)
40             {
41                 yield return new Stock(names[random.Next(0, 3)], 
42                     random.Next(1, 100));
43             }
44         }
45 
46         IEnumerator IEnumerable.GetEnumerator()
47         {
48             return GetEnumerator();
49         }
50     }
51 
52     public class Stock
53     {
54         public Stock(string name, int value)
55         {
56             Name = name;
57             Price = value;
58         }
59 
60         public string Name { get; }
61         public int Price { get; }
62     }
63 }

Here’s my problem, if look at the program we can say that we have two different activity. One activity is checking for the Microsoft price and the other is checking for the google price.

Although they both are independent of each other they are occurring in the same program. If for some reason we want to monitor a new stock we have to update the main program and add some lines like below code,

1 if (stock.Name == "Apple")
2     Console.WriteLine($"Apple new price is {stock.Price}");

Now, The observer pattern that allows us to do is separate the monitoring aspect of the stock data from the action of reading the stock data from the stock simulator.

Let’s go step by step and implement the observer pattern for the above problem,

First, we will define a generic interface for observers (subscribers) specifying how they should be updated. In traditional observer pattern, the Update method doesn’t specify any parameters and observers keep a reference of the observable (publisher). But, this approach usually creates a problem like memory leak if we do not clean our observers and observables properly. Hence the below code!

1 public interface IObserver<T>
2 {
3     void Update(T data);           
4 }

Secondly, we will define a generic observable (subject/publisher) class that uses a generic parameter T as a subject. In traditional observer pattern, usually observable is defined as interface first and then get implemented by concrete subjects. However, by using generics this can be simplified in a single type.

 1 public class Observable<T>
 2 {
 3     private List<IObserver<T>> observers = new List<IObserver<T>>();
 4     private T subject;
 5 
 6     public T Subject
 7     {
 8         get => subject;
 9         set 
10         {
11             subject = value;
12             Notify();
13         }
14     }
15 
16     public void Register(IObserver<T> observer)
17     {
18         observers.Add(observer);
19     }
20 
21     public void Unregister(IObserver<T> observer)
22     {
23         observers.Remove(observer);
24     }
25 
26     public void Notify()
27     {
28         foreach (var observer in observers)
29         {
30             observer.Update(subject);
31         }
32     }
33 }

And, finally, we will create our concrete observers for Microsoft and Google stock.

 1 public class GoogleStockObserver : IObserver<Stock>
 2 {
 3     public void Update(Stock data)
 4     {
 5         if (data.Name == "Google" && data.Price > 50)
 6             Console.WriteLine($"Google reached target price {data.Price}");
 7     }
 8 }
 9 
10 public class MicrosoftStockObserver : IObserver<Stock>
11 {
12     public void Update(Stock data)
13     {
14         if (data.Name == "Microsoft")
15             Console.WriteLine($"Microsoft new price is {data.Price}");
16     }
17 }

Now our main program can be written in the following way:

 1 static void Main(string[] args)
 2 {
 3     //This is our Observable also known as publisher that notifies about change
 4     var stockObservable = new Observable<Stock>();
 5 
 6     //observer that monitors microsoft stock
 7     var microsoftObserver = new MicrosoftStockObserver();
 8     //here microsoftObserver gets register with stockObservable 
 9     //as microsoftObserver wants to get notified when there is a 
10     //change made inside the subject.
11     stockObservable.Register(microsoftObserver);
12 
13     //observer that monitors google stock
14     var googleObserver = new GoogleStockObserver();
15     //here googleObserver gets register with stockObservable 
16     //as googleObserver wants to get notified when there is a 
17     //change made inside the subject.
18     stockObservable.Register(googleObserver);
19 
20     //our same old simulator
21     var stockSimulator = new StockSimulator();
22     //code that updates the subject
23     foreach (var stock in stockSimulator)
24         stockObservable.Subject = stock; //this will cause for 
25 
26     Console.ReadLine();
27 }

Let’s see everything together,

  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 
  5 class Program
  6 {
  7     static void Main(string[] args)
  8     {
  9         //This is our Observable also known as publisher 
 10         //that notifies about change
 11         var stockObservable = new Observable<Stock>();
 12 
 13         //observer that monitors microsoft stock
 14         var microsoftObserver = new MicrosoftStockObserver();
 15         //here microsoftObserver gets register with stockObservable 
 16         //as microsoftObserver wants to get notified when there is a 
 17         //change made inside the subject.
 18         stockObservable.Register(microsoftObserver);
 19 
 20         //observer that monitors google stock
 21         var googleObserver = new GoogleStockObserver();
 22         //here googleObserver gets register with stockObservable 
 23         //as googleObserver wants to get notified when there is a 
 24         //change made inside the subject.
 25         stockObservable.Register(googleObserver);
 26 
 27         //our same old simulator
 28         var stockSimulator = new StockSimulator();
 29         //code that updates the subject
 30         foreach (var stock in stockSimulator)
 31             stockObservable.Subject = stock; //this will cause for 
 32 
 33         Console.ReadLine();
 34     }
 35 
 36     public class GoogleStockObserver : IObserver<Stock>
 37     {
 38         public void Update(Stock data)
 39         {
 40             if (data.Name == "Google" && data.Price > 50)
 41                 Console.WriteLine($"Google reached target price {data.Price}");
 42         }
 43     }
 44 
 45     public class MicrosoftStockObserver : IObserver<Stock>
 46     {
 47         public void Update(Stock data)
 48         {
 49             if (data.Name == "Microsoft")
 50                 Console.WriteLine($"Microsoft new price is {data.Price}");
 51         }
 52     }
 53 
 54     //An generic interface for Observers specifying how they should be updated
 55     public interface IObserver<T>
 56     {
 57         void Update(T data);           
 58     }
 59 
 60     public class Observable<T>
 61     {
 62         private List<IObserver<T>> observers = new List<IObserver<T>>();
 63         private T subject;
 64 
 65         public T Subject
 66         {
 67             get => subject;
 68             set 
 69             {
 70                 subject = value;
 71                 Notify();
 72             }
 73         }
 74 
 75         public void Register(IObserver<T> observer)
 76         {
 77             observers.Add(observer);
 78         }
 79 
 80         public void Unregister(IObserver<T> observer)
 81         {
 82             observers.Remove(observer);
 83         }
 84 
 85         public void Notify()
 86         {
 87             foreach (var observer in observers)
 88             {
 89                 observer.Update(subject);
 90             }
 91         }
 92     }
 93 
 94     public class StockSimulator : IEnumerable<Stock>
 95     {
 96         Random random;
 97         string[] names = new string[3] { "Microsoft", "Google", "Apple" };
 98 
 99         public StockSimulator()
100         {
101             random = new Random(1024);
102         }
103 
104         public IEnumerator<Stock> GetEnumerator()
105         {
106             for (int i = 0; i < 20; i++)
107             {
108                 yield return new Stock(names[random.Next(0, 3)],
109                     random.Next(1, 100));
110             }
111         }
112 
113         IEnumerator IEnumerable.GetEnumerator()
114         {
115             return GetEnumerator();
116         }
117     }
118 
119     public class Stock
120     {
121         public Stock(string name, int value)
122         {
123             Name = name;
124             Price = value;
125         }
126 
127         public string Name { get; }
128         public int Price { get; }
129     }
130 }

Now, We have discussed before that when observers lose interest in the subject, they simply unregister from the subject. To implement this all we need to do is update our Subscribe method to return an object that will help us to unregister the passed observer.

1 public Unsubscriber<T> Subscribe(IObserver<T> observer)
2 {
3     if(!observers.Contains(observer))
4         observers.Add(observer);
5     return new Unsubscriber<T>(observers, observer);
6 }

Now, here the Unsubscriber<T> is a generic type that maintains the list of observers and the observer to be unsubscribed from the list, i.e the observer we want to remove from the list. Below is the code for the same,

 1 public class Unsubscriber<T> : IDisposable
 2 {
 3     private List<IObserver<T>> observers;
 4     private IObserver<T> observer;
 5 
 6     public Unsubscriber(List<IObserver<T>> observers, IObserver<T> observer)
 7     {
 8         this.observers = observers;
 9         this.observer = observer;
10     }
11 
12     public void Dispose()
13     {
14         observers.Remove(observer);
15     }
16 }

The action of removing the observer from the list of observers unsubscribe the observer from the subject as our subject has reference to the same list.

Also, the code, of removing the observer from the list, is written within the dispose method. This enables us to use the using statement if we want to unsubscribe more elegantly when the operation defined within the using scope is completed.

After making the above changes, our Observable<T> class will look like the code below.

 1 public class Observable<T>
 2 {
 3     private List<IObserver<T>> observers = new List<IObserver<T>>();
 4     private T subject;
 5 
 6     public T Subject
 7     {
 8         get => subject;
 9         set
10         {
11             subject = value;
12             Notify();
13         }
14     }
15 
16     public Unsubscriber<T> Subscribe(IObserver<T> observer)
17     {
18         if(!observers.Contains(observer))
19             observers.Add(observer);
20         return new Unsubscriber<T>(observers, observer);
21     }
22 
23     public void Notify()
24     {
25         foreach (var observer in observers)
26         {
27             observer.Update(subject);
28         }
29     }
30 }
31 
32 public class Unsubscriber<T> : IDisposable
33 {
34     private List<IObserver<T>> observers;
35     private IObserver<T> observer;
36 
37     public Unsubscriber(List<IObserver<T>> observers, IObserver<T> observer)
38     {
39         this.observers = observers;
40         this.observer = observer;
41     }
42 
43     public void Dispose()
44     {
45         observers.Remove(observer);
46     }
47 }

We can go one step further and provide unsubscribe functionality to our observers too. As this will require some implementation we will make our observer as an abstract class instead of an interface.

 1 public abstract class Observer<T>
 2 {
 3     private Unsubscriber<T> cancellation;
 4 
 5     public abstract void Update(T data);
 6     public void Subscribe(Observable<T> provider)
 7     {
 8         cancellation = provider.Subscribe(this);
 9     }
10 
11     public virtual void Unsubscribe()
12     {
13         cancellation.Dispose();
14     }
15 }

Here all we did is created a Subscribe method that takes an observable and pass current observer object to its Subscribe method and keep a reference of the cancellation object returned by the method, then we use this object in Unsubscribe method to unsubscribe with the provider.

Now, we can write the client code in the following manner:

1 var stockObservable = new Observable<Stock>();
2 
3 var microsoftObserver = new MicrosoftStockObserver();
4 microsoftObserver.Subscribe(stockObservable); //this is more intuitive

above code is more intuitive, instead of,

1 var stockObservable = new Observable<Stock>();
2 
3 var microsoftObserver = new MicrosoftStockObserver();
4 stockObservable.Subscribe(microsoftObserver); //this is Ok too :p

Also, we can now do this in the client code,

 1 static void Main(string[] args)
 2 {
 3     var stockObservable = new Observable<Stock>();
 4 
 5     var microsoftObserver = new MicrosoftStockObserver();
 6     microsoftObserver.Subscribe(stockObservable);
 7 
 8     var googleObserver = new GoogleStockObserver();
 9     googleObserver.Subscribe(stockObservable);
10 
11     stockObservable.Subject = new Stock("Microsoft", 10);
12     microsoftObserver.Unsubscribe();
13     stockObservable.Subject = new Stock("Microsoft", 20);
14     stockObservable.Subject = new Stock("Microsoft", 30);
15     microsoftObserver.Subscribe(stockObservable);
16     stockObservable.Subject = new Stock("Microsoft", 40);
17     stockObservable.Subject = new Stock("Google", 60);
18     googleObserver.Unsubscribe();
19     stockObservable.Subject = new Stock("Google", 70);
20     stockObservable.Subject = new Stock("Google", 80);
21     googleObserver.Subscribe(stockObservable);
22     stockObservable.Subject = new Stock("Google", 90);
23 
24     Console.ReadLine();
25 }

Push And Pull Mechanism Observer Pattern

Now,

When implementing the Observer pattern, there are two main approaches to consider: the ‘push’ model and the ‘pull’ model.

In the ‘push’ model, the subject (i.e. the Observable) sends the observer on notification all the data it will need. The observer doesn’t need to query the subject for information. In the ‘pull’ model, the subject merely notifies the observer that something happened, and the observer queries the subject based to get the information it needs.

Please note,

In both mechanisms, it is always the responsibility of an Observable object to notify all the subscribed observers, the difference lies whether the observer gets the exact data it wants (Push) or it has to extract the required data (Pull).

Let’s discuss the pros and cons of both approaches:

Push

The main advantage of the ‘push’ model is the lower coupling between the observer and the subject. The observer doesn’t need to know anything about the subject to query it. If it needed to, we’d need to do one of the following: A- do downcast on the side of the observer to invoke class-specific get methods on the subject. This is bad. B- make the Observable interface more class-specific, offering specific get methods, thus making the relationship between the observer and subject less general and making things more coupled.

By implementing the ‘push’ model, we avoid all of this.

However, the disadvantage is less flexibility: the subject may not always know what exact information the observers need to send it to them. This will often mean more specific Observer interfaces, such as AgeObserver that are notified when the ‘age’ of the subject is changed, and HeightObserver which are sent the current height of the subject on the notification.

This is one option. The other is the subject sending a whole lot of information encapsulated in an Info object of some sort and have the observers query it from there. But again, we can’t be sure we’re sending the correct info. So it’s either this or forcing the observers to implement more specific Observer interfaces, which tightens the coupling on the observer’s side.

Pull

The main disadvantages of the ‘pull’ model are that the observers would have to know things about the subject to query the right information, which leads A- to downcasting (ugly), or B- favorably to more specific Observable interfaces, that offer more specific accessor methods. For example AgeObservable offers a getAge() method.

The advantage of this is more flexibility. Each observer can decide for itself what to query, without relying on the subject to send the correct information.

Reactive Extensions for .NET

The push model implemented by Reactive Extensions for .NET and is represented by the two interfaces IObservable<T> and IObserver<T>. These interfaces are provided by .NET Framework 4.0 base class library.

You can implement them too in our existing classes like this:

 1 public abstract class Observer<T> : IObserver<T>
 2 {
 3     private Unsubscriber<T> cancellation;
 4 
 5     public void Subscribe(Observable<T> provider)
 6     {
 7         cancellation = provider.Subscribe(this);
 8     }
 9 
10     public virtual void Unsubscribe()
11     {
12         cancellation.Dispose();
13     }
14 
15     public abstract void OnNext(T value);
16 
17     public abstract void OnError(Exception error);
18 
19     public abstract void OnCompleted();
20 }
21 
22 public class Observable<T> : IObservable<T>
23 {
24     private List<Observer<T>> observers = new List<Observer<T>>();
25     private T subject;
26 
27     public T Subject
28     {
29         get => subject;
30         set
31         {
32             subject = value;
33             Notify();
34         }
35     }
36 
37     public void Notify()
38     {
39         foreach (var observer in observers)
40         {
41             observer.OnNext(subject);
42         }
43     }
44 
45     public Unsubscriber<T> Subscribe(Observer<T> observer)
46     {
47         if (!observers.Contains(observer))
48             observers.Add(observer);
49         return new Unsubscriber<T>(observers, observer);
50     }
51 
52     IDisposable IObservable<T>.Subscribe(IObserver<T> observer)
53     {
54         return Subscribe(observer as Observer<T>);
55     }
56 
57     public void Completed()
58     {
59         foreach (var observer in observers)
60             observer.OnCompleted();
61     }
62 
63     public void Error(Exception e)
64     {
65         foreach (var observer in observers)
66             observer.OnError(e);
67     }
68 }

From the above code, you may have noticed, instead of Notify method IObserver relies on OnNext method. The thing is reactive programming represents asynchronous and event-based programs using observable sequences. Reactive Extensions also represents data sequences as observable sequences. An application can subscribe to these observable sequences to receive asynchronous notifications as new data arrive.

In addition to implementing the observer design pattern, you may love to explore libraries that are built using the IObservable<T> and IObserver<T> interfaces. For example, Reactive Extensions for .NET consist of a set of extension methods and LINQ standard sequence operators to support asynchronous programming.

Note: Typically, a Observable implements the Subscribe method by adding a particular observer to a subscriber list that is represented by a collection object, and it implements the Dispose method by removing a particular observer from the subscriber list. So, It could happen that the provider and observer may both try to remove the same member from the list. Because of this possibility, both the Subscribe and Dispose methods should be thread-safe. Typically, this involves using a concurrent collection or a lock. Implementations that are not thread-safe should explicitly document that they are not.

Delegates And Events In C#

Now, In C# you can implement the same idea of observer pattern using Delegates and Events which is really more concise and elegant way of writing this pattern.

Here, Delegate form the basis for the event system in C#. For more information, see my blog post Delegates And Events In C#.

An event is a special kind of delegate that facilitates event-driven programming. Events are class members that cannot be called outside of the class regardless of their access specifier. So, for example, an event declared to be public would allow other classes the use of += and -= on the event, but firing the event (i.e. invoking the delegate) is only allowed in the class containing the event.

Typically, an event is created in the subject/observables and registration of observers is made through the delegate callback mechanism. Observers provide the delegate callback implementation that would be called by the subject when the event is raised.

Let’s see the example,

  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 
  5 class Program
  6 {
  7     static void Main(string[] args)
  8     {
  9         var stockObservable = new StockObservable();
 10         var microsoftObserver = new MicrosoftStockObserver(stockObservable);
 11         var googleObserver = new GoogleStockObserver(stockObservable);
 12 
 13         var stockSimulator = new StockSimulator();
 14         foreach (var stock in stockSimulator)
 15             stockObservable.Subject = stock;
 16         Console.ReadLine();
 17     }
 18 
 19     public class StockObservable
 20     {
 21         private Stock subject;
 22 
 23         /*
 24         an event declared to be public would allow other classes the use of += and -= on
 25         the event, but firing the event (i.e. invoking the delegate) is only allowed in 
 26         the class containing the event.
 27 
 28         The EventHandler delegate is a predefined delegate that specifically represents
 29         an event handler method for an event that generate data of type define in generic
 30         argument EventHandler<TEventArgs> delegate class.
 31         */
 32         public event EventHandler<StockChangeEventArgs> StockChangeEvent = delegate { };
 33 
 34         public Stock Subject
 35         {
 36             get => subject;
 37             set
 38             {
 39                 subject = value;
 40 
 41                 //invoking the delegate
 42                 StockChangeEvent(this, new StockChangeEventArgs(subject));
 43             }
 44         }
 45     }
 46 
 47     //This class represents the data generated by the above event
 48     public class StockChangeEventArgs : EventArgs
 49     {
 50         public StockChangeEventArgs(Stock stock)
 51         {
 52             Stock = stock;
 53         }
 54 
 55         public Stock Stock { get; }
 56     }
 57 
 58     public class GoogleStockObserver
 59     {
 60         public GoogleStockObserver(StockObservable stockTicker)
 61         {
 62             /*
 63             GoogleStockObserver can subscribe to the event by adding 
 64             StockChange method to the event delegate
 65             */
 66             stockTicker.StockChangeEvent += StockChange;
 67         }
 68 
 69         private void StockChange(object sender, StockChangeEventArgs e)
 70         {
 71             var data = e.Stock; //gets the data from the event
 72             if (data.Name == "Google" && data.Price > 50)
 73                 Console.WriteLine($"Google reached target price {data.Price}");
 74         }
 75     }
 76 
 77     public class MicrosoftStockObserver
 78     {
 79         public MicrosoftStockObserver(StockObservable stockTicker)
 80         {
 81             stockTicker.StockChangeEvent += StockChange;
 82         }
 83 
 84         private void StockChange(object sender, StockChangeEventArgs e)
 85         {
 86             var data = e.Stock;
 87             if (data.Name == "Microsoft")
 88                 Console.WriteLine($"Microsoft new price is {data.Price}");
 89         }
 90     }
 91 
 92     public class StockSimulator : IEnumerable<Stock>
 93     {
 94         Random random;
 95         string[] names = new string[3] { "Microsoft", "Google", "Apple" };
 96 
 97         public StockSimulator()
 98         {
 99             random = new Random(1024);
100         }
101 
102         public IEnumerator<Stock> GetEnumerator()
103         {
104             for (int i = 0; i < 20; i++)
105             {
106                 yield return new Stock(names[random.Next(0, 3)],
107                     random.Next(1, 100));
108             }
109         }
110 
111         IEnumerator IEnumerable.GetEnumerator()
112         {
113             return GetEnumerator();
114         }
115     }
116 
117     public class Stock
118     {
119         public Stock(string name, int value)
120         {
121             Name = name;
122             Price = value;
123         }
124 
125         public string Name { get; }
126         public int Price { get; }
127     }
128 
129 }

You can also read my article Publish Subscribe Design Pattern In C# for more in-depth knowledge of this concept.

Where To Apply Observer Pattern?

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

  • When a change to one object requires changing others, and you don’t know how many objects need to be changed.

  • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.

Note: You can download the complete solution demo from my github repository.

Further Reading

  • Observer Design Pattern Best Practices - In the .NET Framework, the observer design pattern is implemented using the IObservable<T> and IObserver<T> interfaces. This post describes the best practices that developers should follow when implementing the observer design pattern using these interfaces.

  • Lesson 07.3: Sending Messages from the ViewModel to the View by Scott Lilly - This is a lesson from Scott’s tutorial - ‘Learn C# by Building a Simple RPG’. In this lesson, Scott creates a way to send messages from the GameSession (ViewModel), to the UI (View). He does this by having the ViewModel “raise an event”, and have the View “subscribe” to that event.

  • Observer by Bob Nystrom - This is a chapter from Bob’s book ‘Game Programming Patterns’ that explains the Observer pattern from a game developer perspective.

Observer Pattern C#
Share this

Subscribe to Code with Shadman