开发者

Observer pattern C# using generics

开发者 https://www.devze.com 2022-12-15 17:11 出处:网络
I am trying to implement the observer pattern with a slight twist, the Subject and Observer are the same class. For example,

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

精彩评论

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