如何重构重复的事件处理代码

发布于 2024-10-03 12:19:27 字数 707 浏览 3 评论 0原文

我有以下类,它允许某些对象订阅更改事件。问题是我还有类 B 和 C 需要此功能,允许对象订阅相同类型的事物。我们当然不想复制和粘贴这种行为。

我们考虑过从公共基类继承,但是我们所有的类(包括 A、B 和 C)都已经从公共基类继承。我们不想将此行为添加到 BaseClass 中,因为从 BaseClass 继承的其他类 E、F、G 不需要此行为。

有更好的解决方案吗?

public class A : BaseClass
{

    /*other properties and code */

    public event EventHandler OnChange;
    private bool _hasChanged;
    public bool HasChanged
    {
        get { return _hasChanged; }
        set
        {
            _hasChanged = value;
            //only need to notify when we've changed.
            if (value)
            {
                if (OnChange != null)
                    OnChange(this, EventArgs.Empty);
            }
        }
    }
}

I have the following class that lets certain objects subscribe to a change event. The problem is that I also have classes B, and C that need this functionality that allow objects to subscribe to the same kind of thing. We certainly don't want to copy and paste this behaviour.

We've considered inheriting from a common base class, but all our classes including A, B, and C already inherit from a common BaseClass. And we don't want to add this behaviour to BaseClass because our other classes E,F,G that inherit from BaseClass don't need this behaviour.

Is there a better solution?

public class A : BaseClass
{

    /*other properties and code */

    public event EventHandler OnChange;
    private bool _hasChanged;
    public bool HasChanged
    {
        get { return _hasChanged; }
        set
        {
            _hasChanged = value;
            //only need to notify when we've changed.
            if (value)
            {
                if (OnChange != null)
                    OnChange(this, EventArgs.Empty);
            }
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

双马尾 2024-10-10 12:19:27

考虑一种面向方面的编程方法,例如 PostSharp 示例 中使用的方法。它允许您使用属性注入此类样板代码。

如果您创建了适当的方面,则可以使用如下代码:

public class A : BaseClass
{
    public event EventHandler OnChanged;

    [ChangedNotify("OnChanged")]
    public bool HasChanged { get; set; }
}

或者,如果想法是为多个属性使用单个 OnChange 事件,您可以将其硬编码到方面中,从而减少代码到

public class A : BaseClass
{
    [NotifyOnChanged]
    public bool HasChanged { get; set; }
}

Consider an aspect-oriented programming approach, like the one used in this PostSharp example. It would allow you to inject that kind of boilerplate code using attributes.

If you created the appropriate aspect, you could then have code like:

public class A : BaseClass
{
    public event EventHandler OnChanged;

    [ChangedNotify("OnChanged")]
    public bool HasChanged { get; set; }
}

or, if the idea is to have a single OnChange event for multiple properties, you could just hard-code that into the aspect, reducing your code to

public class A : BaseClass
{
    [NotifyOnChanged]
    public bool HasChanged { get; set; }
}
命硬 2024-10-10 12:19:27

如果我们暂时不使用继承怎么办?

1-假设,不是从公共基类继承,而是用实现事件机制的对象来编写需要事件机制的客户端类。

假设我们的类是

 public class EventNotifier
{
    public event EventHandler OnChange;
    private bool _hasChanged;
    public bool HasChanged
    {
        get { return _hasChanged; }
        set
        {
            _hasChanged = value;
            //only need to notify when we've changed. 
            if (value)
            {
                if (OnChange != null)
                    OnChange(this, EventArgs.Empty);
            }
        }
    }
}

2-

 public class A
{
    private EventNotifier eventNotifier;
    public EventNotifier MyEventNotifier { get { return eventNotifier; } }

    public A()
    {
        eventNotifier = new EventNotifier();
    }


}

3- 现在你的类 A 的用户(继承/组合类 A 的类)

这是用于如果 B 包含 A

 public class b
{
    A obj ;
    public b()
    {
        obj = new A();
        obj.MyEventNotifier.OnChange += new EventHandler(delegate { Console.WriteLine("Hi"); });
        obj. MyEventNotifier.HasChanged = true;
    }
}

What if we don't use inheritance for a moment?

1- Suppose , Instead of inheriting from a common base class, Compose your client class which requires event mechanism with a object which implement event mechanism.

Suppose our class is

 public class EventNotifier
{
    public event EventHandler OnChange;
    private bool _hasChanged;
    public bool HasChanged
    {
        get { return _hasChanged; }
        set
        {
            _hasChanged = value;
            //only need to notify when we've changed. 
            if (value)
            {
                if (OnChange != null)
                    OnChange(this, EventArgs.Empty);
            }
        }
    }
}

2-

 public class A
{
    private EventNotifier eventNotifier;
    public EventNotifier MyEventNotifier { get { return eventNotifier; } }

    public A()
    {
        eventNotifier = new EventNotifier();
    }


}

3- Now your users of class A ( class which is inherited / composed class A)

this is for if B contains A

 public class b
{
    A obj ;
    public b()
    {
        obj = new A();
        obj.MyEventNotifier.OnChange += new EventHandler(delegate { Console.WriteLine("Hi"); });
        obj. MyEventNotifier.HasChanged = true;
    }
}
负佳期 2024-10-10 12:19:27

您可以考虑在 BaseClass 和 A、B、C 之间引入一个包含常见行为的中间类。这样你就不会污染不需要该行为的 E、F、G。

             BaseClass
  -----------------------------
  |                           |
-----                   NotifyBaseClass
E,F,G                         |
                            -----
                            A,B,C

注意 虽然 AOP 看起来很不错,但我在尝试让 Postsharp 与其他技术(例如 MS Code Analysis 和 MSBuild)一起使用时遇到了重大问题。

You could consider introducing an intermediary class between BaseClass and A,B,C that contains the common behaviour. In this way you will not be polluting E,F,G which do not need the behaviour.

             BaseClass
  -----------------------------
  |                           |
-----                   NotifyBaseClass
E,F,G                         |
                            -----
                            A,B,C

NB Although AOP looks yummy I have had major problems trying to get Postsharp to work with other technologies e.g. MS Code Analysis and MSBuild.

洒一地阳光 2024-10-10 12:19:27

为可通知对象创建一个子类可能是一种可行的方法,但如果将方面以这种方式乘以多种不同的类,则可能会很棘手。另一种方法是将其包含在您的基类中并为其定义一个接口,然后您可以简单地添加相关类的接口。

运行时,只需检查它是否是 IChangeable (或其他内容),然后仅连接到事件

Having a subclass for notifyable objects might be the way to go but it can be tricky with aspects multiplying that way into a wide range of different classes. Another way would to infact include it in your base class and define an interface for it, then you can simply tack on the interface for the relevant classes.

When running yous simply check if it's a IChangeable (or something) and only hook up to the event then

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文