有没有比 if 序列更好的方法来处理事件?
我最近遇到了几个使用这种模式通过硬编码映射来处理事件的对象:
public void handleEvent(Event event)
{
if(event.getCode() == SOME_STATIC_EVENT)
doSomething(event);
if(event.getCode() == ANOTHER_STATIC_EVENT)
doSomethingElse(event);
}
其中 doSomething 函数被实现为同一类的方法。
为了实现更松散的耦合,您建议如何抽象出这种模式?另外,将 0..N 函数映射到触发事件的最佳方法是什么?
I recently ran across several objects implemented to handle events with a hard coded mapping using this pattern:
public void handleEvent(Event event)
{
if(event.getCode() == SOME_STATIC_EVENT)
doSomething(event);
if(event.getCode() == ANOTHER_STATIC_EVENT)
doSomethingElse(event);
}
where doSomething functions are implemented as methods of the same class.
In hopes of striving for looser coupling, how would you suggest abstracting out this pattern? Also, what's the best approach for mapping 0..N functions to a fired event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,基本上您想要做的是创建一个将事件类型映射到接口的数据结构。这是一个以地图形式实现的简单示例。
这使您能够有效地处理大量事件,并动态添加、删除事件并将其重新映射到不同的处理程序。
Yes, basically what you want to do is create a data structure that maps an event type to an interface. Here's a simple one implemented as a map.
This gives you the ability to efficiently handle a large number of events and dynamically add, remove, and remap events to different handlers.
最近有一篇 SOF 帖子类似且足够接近,我的回复 这里可以很好地回答你的问题。
您可以创建自己的界面,而不是可运行的:
There was recently a SOF post that was similar and close enough that my response here can answer your question quite well.
Rather than a runnable, you would make your own interface:
您可以先让代码变得更简洁一些。使用局部变量取出重复的
event.getCode()
。切换到枚举,以便您可以使用switch
。如果存在重复模式,您可以解码为多方法回调接口,就像 AWT 那样。
我建议事件的注册变得更加具体。为每种事件类型注册不同的回调。甚至从事件中取出事件代码,甚至可能删除事件。在工作表下,您可以保留事件代码以映射到处理程序,但这应该是不透明的。这种方法的缺点是匿名内部类目前 (JDK6) 非常冗长,并且类处理效率低下(加载时间和永久代占用空间)。
You can start by making the code a little cleaner. Use a local variable to take out the repeated
event.getCode()
. Switch to enums so you can useswitch
.If there is a repeated pattern you can decode to a multiple method callback interface, like AWT does.
I would suggest that the registration of the even becomes more specific. Register a different callback for each event type. Even as far as taking the event code out of the event, and perhaps removing the event. Under the sheets you might keep the event code for a mapping to handlers, but this should be opaque. The downside to this approach is that anonymous inner classes are currently (JDK6) highly verbose and class handling is inefficient (load times and perm gen footprint).