Observer - Behavioural


Overview:

The Observer Pattern in C# transforms your code into a party invitation dispatcher—celebrating events and notifying party animals. Let's unravel this festive coding tale:

Implementation in C#:

In C#, the Observer Pattern involves defining a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated. Consider a party scenario where guests receive invitations:

// Subject (Party Inviter)
public class PartyInviter
{
    private readonly List<IPartyObserver> partyObservers = new List<IPartyObserver>();

    public void AddObserver(IPartyObserver observer)
    {
        partyObservers.Add(observer);
    }

    public void RemoveObserver(IPartyObserver observer)
    {
        partyObservers.Remove(observer);
    }

    public void NotifyObservers(string invitation)
    {
        foreach (var observer in partyObservers)
        {
            observer.ReceiveInvitation(invitation);
        }
    }
}

// Observer (Party Animal)
public interface IPartyObserver
{
    void ReceiveInvitation(string invitation);
}

// Concrete Observer (Party Animal Implementation)
public class PartyAnimal : IPartyObserver
{
    public string Name { get; }

    public PartyAnimal(string name)
    {
        Name = name;
    }

    public void ReceiveInvitation(string invitation)
    {
        Console.WriteLine($"{Name} received an invitation: {invitation}");
    }
}

Pros:

  1. Loose Coupling: Subjects and observers are loosely coupled, promoting flexibility.

  2. Dynamic Updates: Supports dynamic addition and removal of observers.

  3. Broadcast Notifications: Allows broadcasting events to multiple observers effortlessly.

Cons:

  1. Unintended Updates: Observers may receive updates they are not interested in.

  2. Potential Performance Impact: A large number of observers can impact performance.

When to Use and When Not:

  • Use: When one object's state changes and others need to be notified or when a decoupled and flexible design is desired.

  • Avoid: In scenarios where direct dependencies between objects suffice or when unintended updates could lead to issues.

Usage in .NET Core Framework:

The Observer Pattern is deeply ingrained in the .NET Core framework, especially in event-driven programming. Events and delegates serve as a powerful implementation of the Observer Pattern, allowing objects to subscribe and react to events without explicit dependencies.

Real-Life Example:

Consider an online shopping cart where customers receive updates about their orders. The Observer Pattern is applied:

// Shopping cart subject
var shoppingCart = new ShoppingCart();

// Customers as observers
var customer1 = new Customer("Alice");
var customer2 = new Customer("Bob");

// Customers subscribe to cart updates
shoppingCart.Subscribe(customer1);
shoppingCart.Subscribe(customer2);

// Cart updates trigger notifications to customers
shoppingCart.UpdateCart("Product added: iPhone");

// Output:
// Alice received an update: Product added: iPhone
// Bob received an update: Product added: iPhone

Here, the shopping cart acts as the subject, and customers act as observers, receiving updates about changes in the shopping cart.

In conclusion, the Observer Pattern in C# turns your code into a party invitation dispatcher—celebrating events and notifying party animals. While promoting loose coupling and dynamic updates, developers should be mindful of potential unintended updates and performance considerations. Its reflection in event-driven programming within the .NET Core framework showcases its adaptability, making it a delightful choice for scenarios where code becomes a lively party host, orchestrating events and keeping the celebration dynamic and engaging.


No files yet, migration hasn't completed yet!