我经常遇到这样一种情况,即给定的对象需要有许多侦听器.例如,我可能有
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 对象,该对象将具有 TigerListeners.现在,TigerListeners 和 ElephantListeners 是完全不同的:
but I'll have many such situations. That is, I'll also have a Tiger object that'll have TigerListeners. Now, TigerListeners and ElephantListeners 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.
更多推荐
爪哇.实现监听器的正确模式
发布评论