使用泛型的观察者模式 C#
我试图稍微改变一下观察者模式,主题和观察者是同一个类。例如,
class myclass
{
public delegate void UpdateHandler(object sender);
public event UpdateHandler UpdateEvent;
public Attach(myclass obj){ // use delegate to attach update function of obj}
public Update(object sender){ // do something with sender}
public Notify() { // use UpdateEvent to update all attached obj's }
}
这应该可以正常工作。现在我想消除每次有更新事件时装箱和拆箱所带来的性能损失,因此我删除了基于“对象”的实现并尝试使用泛型。例如,
class myclass<Tin, Tout>
{
public delegate void UpdateHandler(Tout sender);
public event UpdateHandler UpdateEvent;
public Attach(myclass<Tin,Tout> obj)
{ // use delegate to attach update function of obj}
public Update(Tin sender){ // do something with sender}
public Notify()
{ // use UpdateEvent to update all attached obj's
// but now we have to send Tout
}
}
这不起作用,因为我有一个 EventHandler,它可以是 Tin 或 Tout,但不能同时是两者。我该如何解决这个问题?也欢迎任何其他改变设计的建议。非常感谢您阅读本文,我希望这足以清楚地理解这个问题。
I am trying to implement the observer pattern with a slight twist, the Subject and Observer are the same class. For example,
class myclass
{
public delegate void UpdateHandler(object sender);
public event UpdateHandler UpdateEvent;
public Attach(myclass obj){ // use delegate to attach update function of obj}
public Update(object sender){ // do something with sender}
public Notify() { // use UpdateEvent to update all attached obj's }
}
This should work fine. Now I want to remove the performance penalty imposed by boxing and unboxing everytime i have an update event, thus I remove the "object" based implementation and am trying to use generics. For example,
class myclass<Tin, Tout>
{
public delegate void UpdateHandler(Tout sender);
public event UpdateHandler UpdateEvent;
public Attach(myclass<Tin,Tout> obj)
{ // use delegate to attach update function of obj}
public Update(Tin sender){ // do something with sender}
public Notify()
{ // use UpdateEvent to update all attached obj's
// but now we have to send Tout
}
}
This does not work, because I have one EventHandler, it can either be Tin or Tout, but not both. How do I get around this ? Any other suggestions to change design also welcome. Thanks very much for reading this and I hope this is clear enough to understand the question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也更改您的事件处理程序:
Change your event handler too:
查看此问题和回复。这是带有强类型泛型的 pub/sub 的一个非常好的实现。
Check out this question and responses. It is a very good implementation of pub/sub with strongly-typed generics.