Observer Examples:

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

Creating a Stock Ticker

We want to create a stock ticker that notifies us of updates on prices for specific stocks of our choosing. One way to accomplish this is using the Observer Pattern to subscribe to specific stock symbols. Using the Observer Pattern, we can create observers that listen for an update from a specific stock, then update the internal price.

The Stock Ticker Subject:

class StockTicker
{
   private observersRoot: TickerObserver;

   constructor()
   {
       this.observersRoot = null;
   }

   // Head-first insertion into the list:
   public addObserver(observer: TickerObserver)
   {
       observer.next = this.observersRoot;
       this.observersRoot = 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 notify(tickerSymbol: string, price: number)
   {
       let tmp = this.observersRoot;
       while(tmp != null)
       {
           tmp.update(tickerSymbol, price);
           tmp = tmp.next;
       }
   }
}

Ticker Observer:

class TickerObserver
{
   public next: TickerObserver;

   private symbol: string;
   private lastPrice: number;

   constructor(symbol: string)
   {
       this.next = null;
       this.symbol = symbol;
       this.lastPrice = 0.0;

   }

   // 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 update(symbol:string, price: number)
   {
       if(this.symbol == symbol)
       {
           this.lastPrice = price;
       }
   }

   public getTicker(): string
   {
       return this.symbol + " : " + this.lastPrice;
   }
}

Find any bugs in the code? let us know!