本文介绍了在Java中避免'instanceof'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(可能是常见的)问题,它现在让我感到困惑:

I have the following (maybe common) problem and it absolutely puzzles me at the moment:

有几个生成的事件对象扩展了抽象类活动我想把它们分成会话豆,比如

There are a couple of generated event objects which extends the abstract class Event and I want to divide them to Session Beans, like

public void divideEvent(Event event) {
    if (event instanceof DocumentEvent) {
        documentGenerator.gerenateDocument(event);
    } else if (event instanceof MailEvent) {
        deliveryManager.deliverMail(event);
        ...
    }
    ...

}

但是将来可能会有两种以上的事件类型,所以if-else会很长并且可能不可读。另外我认为 instanceof 在这种情况下并不是真正的最佳做法。

But there could be more than two event types in future, so the if-else will be long and maybe unreadable. Additionally I think instanceof is not really "best practice" in this case.

我可以添加一个抽象方法事件类型并将它们分开但我必须在每个实体中注入特定的会话Bean。

I could add an abstract method to the Event type and have them divide itself but then I have to inject the specific Session Beans within each entity.

有什么提示可以解决这个问题吗?

Is there any hint to achieve a "pretty" solution for this problem?

感谢您的帮助!

推荐答案

最简单的方法是让事件提供一个你可以调用的方法,以便事件知道该怎么做。

The simplest approach is to have the Event provide a method you can call so the Event knows what to do.

interface Event {
    public void onEvent(Context context);
}

class DocumentEvent implements Event {
    public void onEvent(Context context) {
         context.getDocumentGenerator().gerenateDocument(this);
    }
}

class MailEvent implements Event {
    public void onEvent(Context context) {
         context.getDeliveryManager().deliverMail(event);
    }
}


class Context {
    public void divideEvent(Event event) {
        event.onEvent(this);
    }
}

这篇关于在Java中避免'instanceof'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:48