开发者

Observer pattern C# using generics

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.


Change your event handler too:

public delegate void UpdateHandler<Tin>(Tin sender); 

public event UpdateHandler<Tin> UpdateEvent; 


Check out this question and responses. It is a very good implementation of pub/sub with strongly-typed generics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜