Observer Examples:

Java
Java
Python
Python
PHP
PHP
C#
C#
C++
C++
TypeScript
TypeScript
▸ Observer Quick Review

Observer Pattern in C#

In this example, we'll be creating a stock ticker demo that uses the Observer Pattern to broadcast stock symbols out to observers. If an observer is looking for a particular stock symbol, it will update the price that is also sent across.

Observer:

   public class TickerObserver
   {
       // The symbol that this observer will monitor:
       string symbol;
       // The price last observed by the subject:
       float lastPrice;

       public TickerObserver(string symbol)
       {
           this.symbol = symbol;
           lastPrice = 0.0f;
       }

       // In this example, we only update the price if it's for our symbol.
       // In a more advanced design, you could designate an observer per ticker symbol to be more efficient.
       public void Update(string symbol, float price)
       {
           if(symbol.Equals(this.symbol))
           {
               this.lastPrice = price;
           }
       }

       // When the client wants to be updated on the current ticker status, this can be called:
       public string GetTicker()
       {
           return symbol + " : " + lastPrice.ToString();
       }

   }

Subject:

   using System.Collections.Generic;

   public class StockTicker
   {
       // For brevity, we'll be using a built-in List structure:
       List<TickerObserver> observers;

       public StockTicker()
       {
           observers = new List<TickerObserver>();
       }

       public void AddObserver(TickerObserver observer)
       {
           observers.Add(observer);
       }

       public void RemoveObserver(TickerObserver observer)
       {
           observers.Remove(observer);
       }

       // In our design, we're using one observer for all stock symbols.
       // This design can be improved on further by designating one subject per ticker symbol!
       public void Notify(string tickerSymbol, float price)
       {
           // Notify all the observers of the price update.
           foreach(TickerObserver observer in observers)
           {
               observer.Update(tickerSymbol, price);
           }
       }
   }

Find any bugs in the code? let us know!