问题描述
所有我想要做的是实现观察者模式。
所以,我想出了这个解决方案:
我们有一个PoliceHeadQuarters,其主要工作是向所有订阅者发送通知。考虑到DSP,Inspector和SubInspector类已订阅PoliceHeadQuarters。
使用事件和代表我写了
public class HeadQuarters
{
public delegate void NewDelegate(object sender,EventArgs e);
public event EventHandler NewEvent;
public void RaiseANotification()
{
var handler = this.NewEvent;
if(handler!= null)
{
handler(this,new EventArgs());
}
}
}
public class SubInspector
{
public void Listen(object sender,EventArgs e)
{
MessageBox.Show(string.Format(event sender received by sender = {0} with eventArguments = {1},sender,e.ToString()));
}
}
public class Inspector
{
public void Listen(object sender,EventArgs e)
{
MessageBox .Show(string.Format(event Notification received from sender = {0} with eventArguments = {1},sender,e.ToString()));
}
}
这是我如何调用它
var headQuarters = new HeadQuarters();
var SubInspector = new SubInspector();
var Inspector = new Inspector();
headQuarters.NewEvent + = Inspector.Listen;
headQuarters.NewEvent + = SubInspector.Listen;
headQuarters.RaiseANotification();因此,当调用函数RaiseANotification()时,Inspector和SubInspector类都会收到通知。
p>
似乎DotNet Framework 4,4.5支持一种称为IObserver和IObservable的新方法。
任何人都可以给我一个超简单的例子,使用IObservable和IObserver模式进行上述情况?我只是去搜索互联网上可用的例子太blo肿,难以理解。
我的hinch :(可能我认为是错误的)
DSP:IObserver //,因为它观察总部?
class PoliceHeadQuarters:IObservable //因为这里是我们发送通知的地方?
提前感谢
编辑:有人还表示,MSDN文档对于IObservable @
。
这是一个修改MSDN示例适合您的框架:
public struct Message
{
string text;
public Message(string newText)
{
this.text = newText;
}
public string Text
{
get
{
return this.text;
}
}
}
public class总部:IObservable< Message>
{
public Headquarters()
{
观察者=新列表< IObserver< Message>>();
}
私人列表< IObserver<消息>>观察员;
public IDisposable订阅(IObserver< Message>观察者)
{
if(!observers.Contains(观察者))
观察者。
返回新的取消订阅者(观察者,观察者);
}
私有类取消订阅者:IDisposable
{
私人列表< IObserver< Message>> _observers;
private IObserver< Message> _observer;
public取消订阅者(列表< IObserver< Message>>观察者,IObserver< Message>观察者)
{
this._observers =观察者;
this._observer = observer;
}
public void Dispose()
{
if(_observer!= null&& _observers.Contains(_observer))
_observers。除去(_observer);
}
}
public void SendMessage(Nullable< Message> loc)
{
foreach(观察者中的观察者)
{
if(!loc.HasValue)
observer.OnError(new MessageUnknownException());
else
observer.OnNext(loc.Value);
public void EndTransmission()
{
foreach(var观察者在observers.ToArray())
if(观察者.Contains(observer))
observer.OnCompleted();
observers.Clear();
}
}
public class MessageUnknownException:异常
{
内部MessageUnknownException()
{
}
}
public class Inspector:IObserver< Message>
{
私人IDisposable取消订阅者;
private string instName;
public Inspector(string name)
{
this.instName = name;
}
public string Name
{
get
{
return this.instName;
}
}
public virtual void Subscribe(IObservable< Message> provider)
{
if(provider!= null)
取消订阅= provider.Subscribe(this);
}
public virtual void OnCompleted()
{
Console.WriteLine(总部已经完成传输数据到{0},this.Name) ;
this.Unsubscribe();
}
public virtual void OnError(Exception e)
{
Console.WriteLine({0}:无法从总部获取消息,this.Name );
}
public virtual void OnNext(消息值)
{
Console.WriteLine({1}:从总部得到的消息:{0}, value.Text,this.Name);
}
public virtual void Unsubscribe()
{
unsubscriber.Dispose();
}
}
public class Program
{
public static void Main(string [] args)
{
检查器督察1 =新督察(Greg Lestrade);
检查员inspector2 =新检查员(Sherlock Holmes);
总部总部=新总部();
inspector1.Subscribe(总部);
inspector2.Subscribe(总部);
Headquarters.SendMessage(new Message(Catch Moriarty!));
Headquarters.EndTransmission();
Console.ReadKey();
}
}
All I am trying to do is implementing the observer pattern.
So, I came up with this solution:
We have a PoliceHeadQuarters whose primary job is to send notifications to all those who are subscribed to it. Consider that the DSP, Inspector and SubInspector classes are subscribed to PoliceHeadQuarters.
Using Events and Delegates I wrote
public class HeadQuarters
{
public delegate void NewDelegate(object sender, EventArgs e);
public event EventHandler NewEvent;
public void RaiseANotification()
{
var handler = this.NewEvent;
if (handler != null)
{
handler(this, new EventArgs());
}
}
}
public class SubInspector
{
public void Listen(object sender, EventArgs e)
{
MessageBox.Show(string.Format("Event Notification received by sender = {0} with eventArguments = {1}", sender, e.ToString()));
}
}
public class Inspector
{
public void Listen(object sender, EventArgs e)
{
MessageBox.Show(string.Format("Event Notification received by sender = {0} with eventArguments = {1}", sender, e.ToString()));
}
}
and this is how I invoked it
var headQuarters = new HeadQuarters();
var SubInspector = new SubInspector();
var Inspector = new Inspector();
headQuarters.NewEvent += Inspector.Listen;
headQuarters.NewEvent += SubInspector.Listen;
headQuarters.RaiseANotification();
so, both Inspector and SubInspector classes get notification whenever there the function RaiseANotification() is invoked.
It seems that the DotNet Framework 4, 4.5 supports a new way called IObserver and IObservable.
Can anyone give me a super simple example using IObservable and IObserver pattern for the above scenario? I googled only to find the available examples in the internet too bloated and difficult to understand.
My hinch: (probably i think it's wrong)
class DSP : IObserver //since it observes the headquarters ?
class PoliceHeadQuarters: IObservable // since here's where we send the notifications ?
Thanks in advance.
EDIT: Somebody also said that the MSDN documentation is also incorrect for IObservable @ IObservable vs Plain Events or Why Should I use IObservable?.
Here's a modification of MSDN example to fit your framework:
public struct Message
{
string text;
public Message(string newText)
{
this.text = newText;
}
public string Text
{
get
{
return this.text;
}
}
}
public class Headquarters : IObservable<Message>
{
public Headquarters()
{
observers = new List<IObserver<Message>>();
}
private List<IObserver<Message>> observers;
public IDisposable Subscribe(IObserver<Message> observer)
{
if (!observers.Contains(observer))
observers.Add(observer);
return new Unsubscriber(observers, observer);
}
private class Unsubscriber : IDisposable
{
private List<IObserver<Message>> _observers;
private IObserver<Message> _observer;
public Unsubscriber(List<IObserver<Message>> observers, IObserver<Message> observer)
{
this._observers = observers;
this._observer = observer;
}
public void Dispose()
{
if (_observer != null && _observers.Contains(_observer))
_observers.Remove(_observer);
}
}
public void SendMessage(Nullable<Message> loc)
{
foreach (var observer in observers)
{
if (!loc.HasValue)
observer.OnError(new MessageUnknownException());
else
observer.OnNext(loc.Value);
}
}
public void EndTransmission()
{
foreach (var observer in observers.ToArray())
if (observers.Contains(observer))
observer.OnCompleted();
observers.Clear();
}
}
public class MessageUnknownException : Exception
{
internal MessageUnknownException()
{
}
}
public class Inspector : IObserver<Message>
{
private IDisposable unsubscriber;
private string instName;
public Inspector(string name)
{
this.instName = name;
}
public string Name
{
get
{
return this.instName;
}
}
public virtual void Subscribe(IObservable<Message> provider)
{
if (provider != null)
unsubscriber = provider.Subscribe(this);
}
public virtual void OnCompleted()
{
Console.WriteLine("The headquarters has completed transmitting data to {0}.", this.Name);
this.Unsubscribe();
}
public virtual void OnError(Exception e)
{
Console.WriteLine("{0}: Cannot get message from headquarters.", this.Name);
}
public virtual void OnNext(Message value)
{
Console.WriteLine("{1}: Message I got from headquarters: {0}", value.Text, this.Name);
}
public virtual void Unsubscribe()
{
unsubscriber.Dispose();
}
}
public class Program
{
public static void Main(string[] args)
{
Inspector inspector1 = new Inspector("Greg Lestrade");
Inspector inspector2 = new Inspector("Sherlock Holmes");
Headquarters headquarters = new Headquarters();
inspector1.Subscribe(headquarters);
inspector2.Subscribe(headquarters);
headquarters.SendMessage(new Message("Catch Moriarty!"));
headquarters.EndTransmission();
Console.ReadKey();
}
}
这篇关于IObserver和IObservable在C#for Observer vs Delegates,Events中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!