何时使用活动? [英] When to use events?

查看:141
本文介绍了何时使用活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在工作中,我们有一个巨大的框架,并使用事件将数据从其中一部分发送到另一个。我最近开始一个个人项目,我经常想到使用事件来控制我的对象的交互。

At work, we have a huge framework and use events to send data from one part of it to another. I recently started a personnal project and I often think to use events to control the interactions of my objects.

例如,我有一个播放声音效果的Mixer类,最初以为我应该收到事件来发挥音效。然后我决定只让我的课程静态,并调用

For example, I have a Mixer class that play sound effects and I initially thought I should receive events to play a sound effect. Then I decided to only make my class static and call

Mixer.playSfx(SoundEffect)

在我的课程。我有很多这样的例子,我最初想到一个事件的实现,然后改变主意,对自己说,这太复杂了。

in my classes. I have a ton of examples like this one where I initially think of an implementation with events and then change my mind, saying to myself it is too complex for nothing.

所以什么时候应该在项目中使用事件?在某些情况下,事件比其他技术有重大的优势?

So when should I use events in a project ? In which occasions events have a serious advantage over others techniques ?

推荐答案

您通常使用事件来通知用户某些动作或状态变化发生在对象上。通过使用事件,您可以让不同的用户做出不同的反应,通过将用户(及其逻辑)与事件生成器分离,对象变得可重用。

You generally use events to notify subscribers about some action or state change that occurred on the object. By using an event, you let different subscribers react differently, and by decoupling the subscriber (and its logic) from the event generator, the object becomes reusable.

在您的混音器例如,我会有事件发出声音效果的开始和结束。如果我在桌面应用程序中使用它,我可以使用这些事件来在UI中启用/禁用控件。

In your Mixer example, I'd have events signal the start and end of playing of the sound effect. If I were to use this in a desktop application, I could use those events to enable/disable controls in the UI.

这篇关于何时使用活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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