C#事件根据需求通知订阅者

问题描述 投票:-1回答:1

我有一个改变颜色的类Shape,它应该在发生更改时通知订阅者。但是,订阅者希望收到如下通知:

  • Subscriber1只有在Shape颜色变为greenyellowred时才会收到通知
  • Subscriber2只有在Shape颜色变为red时才会收到通知
  • Subscriber3希望随时获得通知,Shape颜色会变为任何颜色

这是我的Shape类

public class Shape  
{  
    public event EventHandler ColorChanged;  

    void ChangeColor()  
    {  
        // set new color 

        OnColorChanged(...);  

    }  

    protected virtual void OnColorChanged(MyEventArgs e)  
    {  
        if(ColorChanged != null)  
        {  
           ColorChanged(this, e);  
        }  
    }  
} 

和我的订阅者

public class Subscriber1
{
    public Subscriber1(Shape shape)
    {
        shape.ColorChanged += new EventHandler(OnColorChanged);
    }

    void OnColorChanged(object sender, EventArgs e)
    {
        // this subscriber wants to get notified only if color changes to green, yellow and red
    }
}

public class Subscriber2
{
    public Subscriber2(Shape shape)
    {
        shape.ColorChanged += new EventHandler(OnColorChanged);
    }

    void OnColorChanged(object sender, EventArgs e)
    {
        // this subscriber wants to get notified only if color changes to red
    }
}

public class Subscriber3
{
    public Subscriber3(Shape shape)
    {
        shape.ColorChanged += new EventHandler(OnColorChanged);
    }

    void OnColorChanged(object sender, EventArgs e)
    {
        // this subscriber wants to get notified every time shape color changes
    }
}

如何让Shape通知这些订户在其首选条件下的颜色变化(即我希望仅在您的颜色变为红色时才收到通知)?

我看到的每个例子都会通知所有订阅者所有更改,我试图这样做

  • 订阅者可以告诉Shape他们想要通知哪些更改
  • 然后,Shape会根据他们的要求通知这些订阅者
c# events event-handling publish-subscribe observer-pattern
1个回答
0
投票

您必须为每个不同的可能订阅选项维护一个委托列表:

private Dictionary<Color, EventHandler> colorChangedHandlers;

private EventHandler color_changed_to_red;
private EventHandler color_changed_to_yellow;
.
.
.
// then, add all of the delegates to the list

订阅者必须打电话

shapeInstance.SubscribeColorChanged(EventHandler handler, params Color[] desiredColors);

然后,你必须实现它,像这样:

public void SubscribeColorChanged(EventHandler handler, params Color[] colors)
{
  foreach (Color c in colors)
  {
    colorChangedHandlers[c] += handler;
  }
}

当然,您还需要伴随的Unsubscribe方法:

public void UnsubscribeColorChanged(EventHandler handler, params Color[] desiredColors)
{
  foreach (Color c in desiredColors)
  {
    foreach (KeyValuePair<Color, EventHandler> kvp in colorChangedHandlers)
    {
      if (kvp.Key == c) {
        EventHandler tmp = kvp.Value;
        tmp -= handler;
      }
    }
  }
}

然后,你将不得不改变你的OnColorChanged方法

protected virtual void OnColorChanged(Color color)
{
  colorChangedEventHandlers[color]?.Invoke(this, EventArgs.Empty);
}

所有这一切只是为了一个ColorChanged事件,可以使用NewColor派生类的EventArgs属性处理!!另外,自定义颜色必须更复杂,因为这只涉及Colors枚举中的值。这可能是可能的,但我不建议任何人没有明确和绝望的需要。

© www.soinside.com 2019 - 2024. All rights reserved.