Alternative to Java's Observable class? [close

2020-05-16 01:12发布

问题:

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.

回答1:

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.



回答2:

I recommend looking into reactive programming. Java has only one implementation that I know of: reactive4java.



回答3:

This article shows a nice implementation of the pattern using Spring Framework. You still need to define your Subject and Observer interfaces (and implementations), but Spring handles the Observer registration to Subjects through XML configuration.