Skip to content

Instantly share code, notes, and snippets.

@dyguests
Created September 18, 2022 07:18
Show Gist options
  • Save dyguests/8441d558437832b4b197bb592f9d64ea to your computer and use it in GitHub Desktop.
Save dyguests/8441d558437832b4b197bb592f9d64ea to your computer and use it in GitHub Desktop.
C#, Unity, 观察者模式, 审查者模式, 观察者模式变体, ISubject, IObserver
namespace Tools
{
public interface IObserver<out T>
{
T Updater { get; }
}
}
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Tools
{
public interface ISubject<T>
{
void AddObserver(IObserver<T> observer);
void RemoveObserver(IObserver<T> observer);
void NotifyObserver([NotNull] Action<T> action);
}
public class DefaultSubject<T> : ISubject<T>
{
private readonly List<IObserver<T>> observers = new();
public void AddObserver(IObserver<T> observer)
{
observers.Add(observer);
}
public void RemoveObserver(IObserver<T> observer)
{
observers.Remove(observer);
}
public void NotifyObserver(Action<T> action)
{
foreach (var observer in observers)
{
action(observer.Updater);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment