问题
C# has the notion of events on a language level, using the reserved keywords event
and delegate
to define publisher and subscriber methods. It has been asked if Java has native support for that but the answer is obviously no. There are several alternatives, which include using AWT/Swing styled events, building my own Observer pattern or using other means of publish/subscribe. It is possible but as one answer said, "just requires a bit more legwork."
In general any implementation follows the same typed approach and could be automated. Java has different mechanisms for meta programming, e.g. AOP or AST transformations. How would one implement the C# events in Java to allow for the least "legwork" possible?
Maybe Project Lombok?
回答1:
If you have a distributed environment, use Akka.
Otherwise you have a few choices
Guava has EvenBus. Guava would be my choice because it has become one of the core libraries that Java projects use, like apache commons, slf4j etc.
Google search for "java event library" reveals a few more choices.
Otherwise, write a class that holds subscribers and dispatches to them the events as they come in. Easy, but careful with concurrency.
来源:https://stackoverflow.com/questions/21007276/how-to-implement-language-level-events-similar-to-c-sharp-in-java