爪哇.实现监听器的正确模式 [英] Java. Correct pattern for implementing listeners
问题描述
我经常遇到这样一种情况,即给定的对象需要有许多侦听器.例如,我可能有
Very typically I have a situation where a given object will need to have many listeners. For instance, I might have
class Elephant {
public void addListener( ElephantListener listener ) { ... }
}
但是我会有很多这样的情况.也就是说,我还将有一个 Tiger
对象,该对象将具有 TigerListener
s.现在,TigerListener
s 和 ElephantListener
s 是完全不同的:
but I'll have many such situations. That is, I'll also have a Tiger
object that'll have TigerListener
s. Now, TigerListener
s and ElephantListener
s are quite different:
interface TigerListener {
void listenForGrowl( Growl qrowl );
void listenForMeow( Meow meow );
}
同时
interface ElephantListener {
void listenForStomp( String location, double intensity );
}
我发现我总是要不断地在每个动物类中重新实现广播机制,而且实现总是相同的.有没有首选的模式?
I find that I always have to keep re-implementing the broadcasting mechanism in each animal class, and the implementation is always the same. Is there a preferred pattern?
推荐答案
不是每个 Listener
都有针对您可以发送的每种事件类型的特定方法,而是更改接口以接受通用 事件
类.然后,您可以根据需要将 Event
子类化为特定的子类型,或者让它包含诸如 double strength
之类的状态.
Instead of each Listener
having specific methods for every event type you can send it, change the interface to accept a generic Event
class. You can then subclass Event
to specific subtypes if you need, or have it contain state such as double intensity
.
TigerListener 和 ElephentListener 然后变成
TigerListener and ElephentListener then become
interface TigerListener {
void listen(Event event);
}
事实上,你可以进一步将此接口重构为一个普通的Listener
:
In fact, you can then further refactor this interface into a plain Listener
:
interface Listener {
void listen(Event event);
}
你的 Listener
实现可以包含他们关心的特定事件所需的逻辑
Your Listener
implementations can then contain the logic that they need for the specific events they care about
class TigerListener implements Listener {
@Overrides
void listen(Event event) {
if (event instanceof GrowlEvent) {
//handle growl...
}
else if (event instance of MeowEvent) {
//handle meow
}
//we don't care about any other types of Events
}
}
class ElephentListener {
@Overrides
void listen(Event event) {
if (event instanceof StompEvent) {
StompEvent stomp = (StompEvent) event;
if ("north".equals(stomp.getLocation()) && stomp.getDistance() > 10) {
...
}
}
}
}
订阅者和发布者之间的关键关系是发布者可以向订阅者发送事件,它不一定可以向订阅者发送某些类型的事件——这种类型的重构将这个逻辑从接口下推到具体实现.
The key relationship between the subscriber and the publisher is that the publisher can send events to the subscribers, it isn't necessarily that it can send it certain types of events - this type of refactoring pushes that logic from the interface down into the specific implementations.
这篇关于爪哇.实现监听器的正确模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!