难道真的事件使代码分离? [英] Do events really make code decoupled?

查看:193
本文介绍了难道真的事件使代码分离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用事件脱钩,我有代码,这里是我的问题:

So I am trying to use events to decouple code that I have and here is my problem:

class WorldHandler
{
    public void Notify(object sender, EventArgs e)
    {
        if (e is CameraMovedEventArgs)
        {
            // handle event
        }

        if (e is MapLoaded)
        {
            // handle event
        }
    }
}

WorldHandler 类听我的应用程序的不同的子系统。那岂不是等于说 WorldHandler 仍然再加上其他子系统?那岂不是访问这个类里面直接这些子系统一样的吗?

WorldHandler class listens to different subsystems of my application. Doesn't that mean that WorldHandler is still coupled with other subsystems? Wouldn't it be the same to access those subsystems inside this class directly?

如果很难理解我问我会添加更多的信息,我的职务。

If it's hard to understand what I am asking I will add additional information to my post.

我没有研究这个问题,我还是发现了这个令人困惑,因为不同的人对如何脱钩的事件代码很不同的意见。

I did research on this problem and I still found this confusing, because different people have very different opinions on how to decouple your code with events.

推荐答案

是你的代码仍然是耦合的,你不仅有一个直接引用类(当你挂钩事件处理程序),但你也有一个参考含有被监视的类的程序集。

Yes your code is still coupled, you not only have a direct reference to the class (when you hook up the event handler) but you also have a reference to the assembly containing the class being watched.

您可以通过在观看类的接口,并只能通过公开的接口上的项目访问它最小化耦合。理想的情况是这个接口应该是第三个比较常见组件,既观察者和watchee参考。您还可以最大限度地减少或使用类似的棱镜中的 EventAggregator消除事件耦合。

You can minimise the coupling by using an interface on the watched class and only accessing it via the items exposed on the interface. Ideally this interface should be in a third "more common" assembly which both the watcher and watchee reference. You can also minimise or eliminate the event coupling by using something like the EventAggregator in Prism.

联轴器本身并不坏,它只是变得更加困难(或昂贵),以换出实现,并取代它们 - 没有适当的去耦还有相当多的工作和更多的风险错误。您的应用程序可能并不需要适当的去耦 - 这取决于你打算用它做什么。

Coupling in itself is not bad, it simply makes it more difficult (or expensive) to swap out implementations and replace them - without proper decoupling there is considerably more work and more risk of bugs. Your application may not need proper decoupling - it depends on what you intend to do with it.

这篇关于难道真的事件使代码分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆