Skip to content

Instantly share code, notes, and snippets.

@GeorgiyRyaposov
Last active April 1, 2020 06:08
Show Gist options
  • Save GeorgiyRyaposov/f9b22c907790c9c74d95ee4403a5a21d to your computer and use it in GitHub Desktop.
Save GeorgiyRyaposov/f9b22c907790c9c74d95ee4403a5a21d to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace Prototype.Scripts.Contexts.Common
{
public interface IObserver<T, Tenum> where Tenum : struct, IConvertible
{
void OnContextChanged(T context, Tenum property);
void OnAttached(T context);
void OnDetached();
}
public interface ISubject<T, Tenum> where Tenum : struct, IConvertible
{
void Attach(IObserver<T, Tenum> observer);
void Detach(IObserver<T, Tenum> observer);
void Notify(Tenum property);
}
public class ContextSubject<T, Tenum> : ISubject<T, Tenum> where Tenum : struct, IConvertible
{
private readonly List<IObserver<T, Tenum>> _observers = new List<IObserver<T, Tenum>>();
private readonly T _context;
public ContextSubject(T context)
{
_context = context;
}
public void Attach(IObserver<T, Tenum> observer)
{
_observers.Remove(observer);
_observers.Add(observer);
observer.OnAttached(_context);
}
public void Detach(IObserver<T, Tenum> observer)
{
_observers.Remove(observer);
observer.OnDetached();
}
public void Notify(Tenum property)
{
for (int i = _observers.Count-1; i >= 0; i--)
{
_observers[i].OnContextChanged(_context, property);
}
}
public void Clear()
{
_observers.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment