例子
教会(Subject)
教会成员(Observer)
public class GuildSubject
{
private List<AbsSubscriber<GuildSubject>> _subscribers;
public GuildSubject(string guildName)
{
GuildName = guildName;
_subscribers = new List<AbsSubscriber<GuildSubject>>();
}
public void AddObserver(AbsSubscriber<GuildSubject> obj)
{
_subscribers.Add(obj);
}
public void RemoveObserver(AbsSubscriber<GuildSubject> obj)
{
_subscribers.Remove(obj);
}
public void SendData(string data)
{
foreach (var subscriber in _subscribers)
{
subscriber.ReceiveData(this, data);
}
}
public string GuildName { get; }
}
public interface IObserver<Subject>
{
void ReceiveData(Subject subject, string data);
}
public abstract class AbsSubscriber<Subject> : IObserver<Subject>
{
public AbsSubscriber(string name)
{
Name = name;
}
public string Name { get; }
public abstract void ReceiveData(Subject subject, string data);
}
public class GuildSubscriber : AbsSubscriber<GuildSubject>
{
public GuildSubscriber(string name) : base(name)
{
}
public override void ReceiveData(GuildSubject subject, string data)
{
Console.WriteLine($"{this.Name}收到{subject.GuildName}教会的消息:{data}");
}
}
private static void SubjectTest()
{
var guildSubject = new GuildSubject("牛逼教会");
guildSubject.AddObserver(new GuildSubscriber("信徒1"));
guildSubject.AddObserver(new GuildSubscriber("信徒2"));
guildSubject.AddObserver(new GuildSubscriber("信徒3"));
guildSubject.SendData("牛逼起来啦");
}