C# Wzorzec Observator

przykład zastosowania subskrybcji do powiadomienia o dostępności produktu za pomocą wzorca obserwator

Product product = new Product("iPhone");

Customer customer1 = new Customer("John");
Customer customer2 = new Customer("Alice");

product.RegisterObserver(customer1);
product.RegisterObserver(customer2);

product.Availability = "Available";
product.UnregisterObserver(customer1);
product.Availability = "Out of Stock";

public class Customer : IObserver
{
    public string Name { get; init; }
    public Customer(string customerName)
    {
        Name = customerName;
    }
    public void Update(string availability)
    {
        Console.WriteLine($"Hello {Name}, Product is now {availability}.");
    }
}

public class Product
{
    private List<IObserver> observers = new List<IObserver>();
    public string Name { get;init; }
    private string _availability;

    public Product(string productName)
    {
        this.Name = productName;
    }

    public string Availability
    {
        get { return _availability; }
        set
        {
            _availability = value;
            NotifyObservers();
        }
    }

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

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

    public void NotifyObservers()
    {
        foreach (IObserver observer in observers)
        {
            observer.Update(Availability);
        }
    }
}

public interface IObserver
{
    void Update(string availability);
}

Wzorzec obserwator z event

using System;

Publisher publisher = new Publisher();
Subscriber subscriber1 = new Subscriber(publisher);
Subscriber subscriber2 = new Subscriber(publisher);
publisher.RaiseEvent("Event 1 occurred.");

public class EventArgs<T> : EventArgs
{
    public T Data { get; private set; }

    public EventArgs(T data)
    {
        Data = data;
    }
}

public class Publisher
{
    // Event declaration
    public event EventHandler<EventArgs<string>> EventOccurred;

    // Method to raise the event
    public void RaiseEvent(string eventData)
    {
        // Check if there are subscribers
        if (EventOccurred != null)
        {
            // Raise the event
            EventOccurred(this, new EventArgs<string>(eventData));
        }
    }
}

public class Subscriber
{
    public Subscriber(Publisher publisher)
    {
        publisher.EventOccurred += HandleEvent;
    }
    private void HandleEvent(object sender, EventArgs<string> e)
    {
        Console.WriteLine($"Event occurred with data: {e.Data}");
    }
}

Scroll to Top