替代Java的可观察类? [英] Alternative to Java's Observable class?

查看:130
本文介绍了替代Java的可观察类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C#世界的Java,其中Observer模式被实现为具有事件关键字的一级语​​言结构。



我看到Java从早期开始就有 Observable 类,但它显然有实现问题,似乎没有被广泛使用。到目前为止,我刚刚在我的Java代码中滚动了我自己的Observer模式的实现,但是我总是不禁想到总是会出现这个样板代码是一个更好的选择。 Swing中有Listener类,但它们似乎不适用于非Swing代码。



这个常见问题是什么推荐的解决方案?

解决方案

通常情况下,观察者模式是在需要时使用特殊解决方案实现的。当涉及到行为模式时,它是最简单的一种:控制观察者列表的两种方法,以及一种通知观察者发生有趣事件的方法。



观察者模式往往在某些域之外太频繁地出现,并且当它出现时,它往往对于应用领域来说太特异,所以通用解决方案没有什么价值。您可以看到 java.util.Observable 类的问题:如果您从 Observable 继承,则必须接受每个可能会传递给您的可能的观察者,这可能对您的申请没有意义:




  • 如果您的对象可以产生两种不同的事件,因此需要两个不同的观察者列表?

  • 如果观察者可能会根据事件影响对象,例如通过能够否决更改?



说,来自Google Guava的EventBus 通过采取截然不同的方法来简化事件生成和处理的工作。
$ b

其他基于注释的技术已经在SO before。


I'm coming to Java from the C# world where the Observer pattern is implemented as a first-class language construct with the event keyword.

I see that Java's had the Observable class since the early days, but it clearly has implementation issues and doesn't seem to be widely used. Thus far I've just been rolling-my-own implementation of the Observer pattern in my Java code but I always can't help but think there must be a better alternative to always turning out this boilerplate code. There are the Listener classes in Swing but they don't seem appropriate for non-Swing code.

What's the recommended solution for this oh-so-common problem? Third-party libraries are ok with me.

解决方案

Usually the observer pattern is implemented with an ad-hoc solution when ever it's needed. When it comes to behavioral patterns it's one of the simplest: two methods to control a list of "observers," and one method that notifies the observers when something interesting happens.

The observer pattern tends to arise too infrequently outside of certain domains, and when it does arise it tends be too specific to the application domain, so generic solutions are of little value. You can see the problem with the java.util.Observable class: if you inherit from Observable you have to accept every possible kind of "observer" that may be passed to you, which likely makes no sense for your application:

  • What if your object can produce two different kinds of events, and thus needs two different lists of observers?
  • What if the observers may influence your object depending on the event, e.g. by being able to veto a change?

That said, EventBus from Google Guava seems to do a pretty good job of simplifying event producing and handling by taking a radically different approach.

Other techniques based on annotations have been discussed on SO before.

这篇关于替代Java的可观察类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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