Anonymous Anonymous - 1 month ago
130 0

Observer Example

C#

Example

using System.Collections.Generic;

public interface Observable
{
    void AddObserver(Observer observer);
    void AddOneShotObserver(Observer observer);
    void RemoveObserber(Observer observer);
    void Notify();
}

public interface Observer
{
    void Update(Observable observable);
}

public class ObservableImpl : Observable
{
    private List<Observer> _observers;
    private List<Observer> _oneShotObservers;

    public void AddObserver(Observer observer)
    {
        _observers.Add(observer);
    }

    public void AddOneShotObserver(Observer observer)
    {
        _oneShotObservers.Add(observer);
        AddObserver(observer);
    }

    public void RemoveObserber(Observer observer)
    {
        _observers.Remove(observer);
    }

    public void Notify()
    {
        foreach (var observer in _observers)
        {
            observer.Update(this);
        }
        // Once finished updating observers remove all one shot observers.
        // We shouldn't try and remove an element within its own enumeration.
        // So by iterating over another collection we can safely remove them from the other collection.
        // Could be done more efficient than this by using a hashmap lookup or something along those lines.
        // This should be fine however as long as its not dealing with a massive collection.        
        foreach (var observer in _oneShotObservers)
        {
            _observers.Remove(observer);
        }
    }
}
Comments