top of page
Writer's pictureamol ankit

Code Chronicles: Unveiling the Observer Pattern

Story begins

Once upon a time, in the realm of software design, we embarked on a journey to unravel the mysteries of the Observer Pattern using the versatile language of C#. Our quest led us to a captivating example—a Stock Market Monitoring System, where the stock market itself played the role of the subject, and eager investors assumed the mantle of observers.



observer in actor of obserinvg stock market.
Investor observing stock market


Act 1: Setting the Stage - The Subject Interface


Our adventure began with the creation of an interface, a set of guidelines for subjects to follow. Named `IStockSubject`, it outlined the methods that would facilitate the registration and notification of observers:

public interface IStockSubject
{
    void RegisterObserver(IStockObserver observer);
    void UnregisterObserver(IStockObserver observer);
    void NotifyObservers();
}

This interface served as the first chapter in our tale, setting the groundwork for the interactions between the stock market and its vigilant observers.


Act 2: The Subject Emerges - Implementing the Concrete Subject


With the stage set, our attention turned to the concrete subject, the Stock Market itself. This entity implemented the `IStockSubject` interface and came to life with its own set of methods and properties:

public class StockMarket : IStockSubject
{
    private List<IStockObserver> observers = new List<IStockObserver>();
    private decimal stockPrice;

    public void RegisterObserver(IStockObserver observer)
    {
        observers.Add(observer);
    }

    public void UnregisterObserver(IStockObserver observer)
    {
        observers.Remove(observer);
    }

    public void NotifyObservers()
    {
        foreach (var observer in observers)
        {
            observer.Update(stockPrice);
        }
    }

    public void SetStockPrice(decimal price)
    {
        stockPrice = price;
        NotifyObservers();
    }
}

The Stock Market, our central character, had the ability to register and unregister observers and, most importantly, notify them of any changes in its stock prices.


Act 3: Introducing the Observers - The Observer Interface


As our story unfolded, a cast of characters was introduced—investors eager to keep a close eye on the stock market. They were defined by the `IStockObserver` interface, which outlined the method they needed to implement to receive updates:

public interface IStockObserver
{
    void Update(decimal stockPrice);
}

The investors were now ready to listen for updates from the stock market.


Act 4: The Drama Unfolds - Implementing the Concrete Observer


The story progressed as individual investors emerged, each represented by a separate class that implemented the `IStockObserver` interface. Named Investor, and each had a unique full name:

public class Investor : IStockObserver
{
    private string name;

    public Investor(string name)
    {
        this.name = name;
    }

    public void Update(decimal stockPrice)
    {
        Console.WriteLine($"{name} received an update. New stock price: {stockPrice}");
    }
}

These investors were now equipped to respond to updates from the stock market, their reactions printed via the console.


Act 5: The Grand Finale - Bringing It All Together


In the final act, our program came to life as we orchestrated the interactions between the stock market and its investors:

class Program
{
    static void Main()
    {
        StockMarket stockMarket = new StockMarket();

        Investor investor1 = new Investor("Chuck Norris");
        Investor investor2 = new Investor("John Cena");

        stockMarket.RegisterObserver(investor1);
        stockMarket.RegisterObserver(investor2);

        // Simulate stock price changes
        stockMarket.SetStockPrice(150.0m);
        stockMarket.SetStockPrice(155.5m);

        // Unregister an observer
        stockMarket.UnregisterObserver(investor1);

        // Simulate more stock price changes
        stockMarket.SetStockPrice(160.2m);
    }
}

Conclusion on Observer Pattern


Thus, concludes our story — a Stock Market Monitoring System where the subject, the Stock Market, communicated seamlessly with its observers, the Investors. The Observer Pattern had been successfully woven into the fabric of our story, illustrating the power of this design pattern.


The End


5,578 views1 comment

1 Comment

Rated 0 out of 5 stars.
No ratings yet

Add a rating
Guest
Nov 23, 2023
Rated 5 out of 5 stars.

This is nice

Like
bottom of page