Created
September 18, 2022 07:18
-
-
Save dyguests/8441d558437832b4b197bb592f9d64ea to your computer and use it in GitHub Desktop.
C#, Unity, 观察者模式, 审查者模式, 观察者模式变体, ISubject, IObserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Tools | |
{ | |
public interface IObserver<out T> | |
{ | |
T Updater { get; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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