public interface IMyObserver
{
public void Update(string myMessage);
public void NotifySubject(string message);
}
public interface IMySubject
{
public void RegisterObserver(IMyObserver o);
public void RemoveObserver(IMyObserver o);
public void NotifyObservers();
public void NotifyMe(string messageFromObserver);
}
及其MyObserver的具体实现:
public class MyObserver : IMyObserver
{
private MySubject _mySubject;
private string _myMessage;
public MyObserver(MySubject mySubject)
{
_mySubject = mySubject;
_mySubject.RegisterObserver(this);
}
public void NotifySubject(string message)
{
_mySubject.NotifyMe(message);
}
public void Update(string myMessage)
{
_myMessage = myMessage;
Console.WriteLine($"Observer have seen this message: {_myMessage}");
}
}
MySubject看起来像这样:
public class MySubject : IMySubject
{
private List<IMyObserver> _observers;
private string _myMessage;
private string _messageFromObserver;
public MySubject() => _observers = new List<IMyObserver>();
public void NotifyObservers()
{
foreach (IMyObserver observer in _observers)
observer.Update(_myMessage);
}
public void RegisterObserver(IMyObserver o) => _observers.Add(o);
public void RemoveObserver(IMyObserver o) => _observers.Remove(o);
public void MyMessageChanged() => NotifyObservers();
public void SetMessage(string message)
{
_myMessage = message;
MyMessageChanged();
}
public string GetMessage() => _myMessage;
public void NotifyMe(string messageFromObserver)
{
_messageFromObserver = messageFromObserver;
Console.WriteLine($"Subject received this message from observer:
{_messageFromObserver}");
}
}
上面的代码可以这样调用:
MySubject mySubject = new ();
MyObserver myObserver = new (mySubject);
// message from subject
mySubject.SetMessage("Hello World!"); // OUTPUT: Observer have seen this message:
// Hello World!
// message from observer to subject
myObserver.NotifySubject("We are notifying subject"); ; // OUTPUT: Subject
// received this message from observer: We are notifying subject
1条答案
按热度按时间pqwbnv8z1#
我们可以通过引用每个观察者拥有的Subject,从Observer* a通知Subject * a。
让我通过C#展示一个例子。这是我们的抽象:
及其
MyObserver
的具体实现:MySubject
看起来像这样:上面的代码可以这样调用: