0% found this document useful (0 votes)
6 views6 pages

Design Patterns in C# Part 4 - Enhancing Event-Driven Architectures With The Observer Pattern - by João Melo - Medium

This document discusses the Observer Pattern in C#, a behavioral design pattern that allows objects (observers) to subscribe to state changes in another object (subject) and react accordingly. It provides a real-world example of a stock market monitoring application, demonstrating how investors can receive notifications of stock price changes without tight coupling between objects. The article concludes by emphasizing the benefits of loose coupling and maintainability in applications using this pattern.

Uploaded by

ekrrmerder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views6 pages

Design Patterns in C# Part 4 - Enhancing Event-Driven Architectures With The Observer Pattern - by João Melo - Medium

This document discusses the Observer Pattern in C#, a behavioral design pattern that allows objects (observers) to subscribe to state changes in another object (subject) and react accordingly. It provides a real-world example of a stock market monitoring application, demonstrating how investors can receive notifications of stock price changes without tight coupling between objects. The article concludes by emphasizing the benefits of loose coupling and maintainability in applications using this pattern.

Uploaded by

ekrrmerder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

19/12/2024, 16:04 Design Patterns in C# Part 4: Enhancing Event-Driven Architectures with the Observer Pattern | by João Melo | Medium

Open in app

Search

Your membership will expire on January 11, 2025 Reactivate membership

Design Patterns in C# Part 4: Enhancing Event-


Driven Architectures with the Observer Pattern
João Melo · Follow
4 min read · Jul 9, 2024

Listen Share More

Mastering Design Patterns in C#: A Comprehensive Series

Introduction

In our previous posts, we explored powerful design patterns like the Strategy
Pattern, Factory Method Pattern, and Decorator Pattern. Today, we delve into the
Observer Pattern, which enhances event-driven architectures by allowing objects

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-4-enhancing-event-driven-architectures-with-the-observer-pattern-33632811964e 1/14
19/12/2024, 16:04 Design Patterns in C# Part 4: Enhancing Event-Driven Architectures with the Observer Pattern | by João Melo | Medium

(observers) to subscribe to state changes in another object (subject) and react


accordingly.

💡Type — Behavioral patterns are concerned with algorithms and the assignment
of responsibilities between objects. They help manage and organize complex
communications between entities in a system.

What is the Observer Pattern?

The Observer Pattern is a behavioral design pattern where an object, known as the
subject, maintains a list of dependents, called observers, and notifies them of any
state changes, usually by calling one of their methods. This pattern establishes a
one-to-many relationship between a subject and its observers, allowing multiple
objects to listen and react to changes in another object.

When to Use the Observer Pattern?

Use the Observer Pattern when you need to establish a dependency between objects
in a way where changes to one object require updating multiple others without
coupling the objects tightly together. It’s ideal for scenarios where decoupling is
important and when objects need to be notified of changes in another object’s state.

Real-world example in C# — Stock Market Monitoring

Imagine you are developing a stock market monitoring application where users
want to track the prices of specific stocks in real-time. Instead of polling for updates
continuously, you can use the Observer Pattern. Each stock (subject) maintains a list
of investors (observers) interested in its price changes. When the price of a stock
changes, all registered investors are notified automatically, allowing them to update
their own displays or take action based on the new price.

Step 1: Define the Subject Interface

The IStock interface defines the contract for a stock object that observers can
subscribe to. It includes methods for attaching and detaching observers, notifying
observers of changes ( Notify() ), and accessing the stock's symbol and price.

public interface IStock


{

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-4-enhancing-event-driven-architectures-with-the-observer-pattern-33632811964e 2/14
19/12/2024, 16:04 Design Patterns in C# Part 4: Enhancing Event-Driven Architectures with the Observer Pattern | by João Melo | Medium

void Attach(IInvestor investor);


void Detach(IInvestor investor);
void Notify();
string GetSymbol();
double GetPrice();
void SetPrice(double price);
}

Step 2: Implement Concrete Subject

The Stock class implements the IStock interface and represents a specific stock
with a symbol and price. It maintains a list of registered investors (observers) and
provides methods to attach, detach, and notify observers when its price changes.
Changes in price trigger notifications to all subscribed investors.

public class Stock : IStock


{
private List<IInvestor> _investors = new List<IInvestor>();
private string _symbol;
private double _price;

public Stock(string symbol, double price)


{
_symbol = symbol;
_price = price;
}

public void Attach(IInvestor investor)


{
_investors.Add(investor);
}

public void Detach(IInvestor investor)


{
_investors.Remove(investor);
}

public void Notify()


{
foreach (var investor in _investors)
{
investor.Update(this);
}
}

public string GetSymbol()


{
https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-4-enhancing-event-driven-architectures-with-the-observer-pattern-33632811964e 3/14
19/12/2024, 16:04 Design Patterns in C# Part 4: Enhancing Event-Driven Architectures with the Observer Pattern | by João Melo | Medium

return _symbol;
}

public double GetPrice()


{
return _price;
}

public void SetPrice(double price)


{
_price = price;
Notify();
}
}

Step 3: Implement Concrete Subject

The IInvestor interface defines the contract for observers interested in monitoring
stock prices. It requires an Update() method that subjects can call to notify
observers of changes in the stock's state.

public interface IInvestor


{
void Update(IStock stock);
}

Step 4: Implement Concrete Observer

The Investor class implements the IInvestor interface and represents an investor
interested in tracking stock prices. Each investor has a name and responds to price
change notifications by displaying a message detailing the stock's symbol and its
new price.

public class Investor : IInvestor


{
private string _name;

public Investor(string name)


{
_name = name;
}
https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-4-enhancing-event-driven-architectures-with-the-observer-pattern-33632811964e 4/14
19/12/2024, 16:04 Design Patterns in C# Part 4: Enhancing Event-Driven Architectures with the Observer Pattern | by João Melo | Medium

public void Update(IStock stock)


{
Console.WriteLine($"Notified {_name} of {_stock.GetSymbol()} price chan
}
}

Step 5: Use the Observers in Client Code

In the Main method of the Program class, we create instances of Stock and
Investor . We attach investors to the stock object to observe price changes
( Attach() ), simulate price updates ( SetPrice() ), and detach investors when they no
longer wish to receive notifications ( Detach() ). This demonstrates how the Observer
Pattern allows dynamic updates and notifications between subjects and observers.

class Program
{
static void Main(string[] args)
{
Stock microsoft = new Stock("MSFT", 350.00);
IInvestor investor1 = new Investor("Investor 1");
IInvestor investor2 = new Investor("Investor 2");

microsoft.Attach(investor1);
microsoft.Attach(investor2);

microsoft.SetPrice(360.00);
microsoft.SetPrice(370.00);

microsoft.Detach(investor2);

microsoft.SetPrice(380.00);
}
}

Conclusion

In this post, we’ve explored the Observer Pattern, which facilitates event-driven
architectures by allowing objects to subscribe and react to changes in another
object’s state. This pattern promotes loose coupling between objects, making it

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-4-enhancing-event-driven-architectures-with-the-observer-pattern-33632811964e 5/14
19/12/2024, 16:04 Design Patterns in C# Part 4: Enhancing Event-Driven Architectures with the Observer Pattern | by João Melo | Medium

easier to maintain and extend applications. We demonstrated its use with a stock
market monitoring example, where investors can track real-time changes in stock
prices.

Stay tuned for our next post in this series, where we’ll explore another design
pattern, the Singleton Pattern, and see how it can further improve your C#
development skills!

👁️

Csharp Design Patterns Observer Pattern Net Core

Event Driven Architecture

Follow

Written by João Melo


80 Followers · 6 Following

Software engineer, specializing in backend development with the C# language and the .NET Core.

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-4-enhancing-event-driven-architectures-with-the-observer-pattern-33632811964e 6/14

You might also like