java - 如何将类的子类型的实例传递给相应的重载方法?

标签 java overloading

我正在重构一个大量使用 case 语句和 emum 的现有状态机。我将其分解为事件和事件处理程序对象,每个对象对应一个状态机。事件处理程序返回新事件以通过状态机传播。

所以,我的代码看起来像这样:

public class Event {
    //common fields and methods
}

public class SpecificEvent extends Event {
    //fields specific to this event
}

public class AnotherEvent extends Event {
    //fields specific to this event
}

public class EventHandler {
    public Event handleEvent(SpecificEvent evt) {
        //do default something
    }
    public Event handleEvent(AnotherEvent evt) {
        //do default something else
    }
}

public class StateOneEventHandler extends EventHandler {
    public Event handleEvent(SpecificEvent evt) {
        //do State1 things
    }
    public Event handleEvent(AnotherEvent evt) {
        //do other State1 things
    }
}

public class StateTwoEventHandler extends EventHandler {
    public Event handleEvent(SpecificEvent evt) {
        //do State2 things
    }
    public Event handleEvent(AnotherEvent evt) {
        //do other State2 things
    }
}

我的问题是:我只在状态机中传递通用事件引用,那么如何为事件调用正确的处理程序?

Event evt = new SpecificEvent();
EventHandler handler = new StateOneEventHandler();

//... later

handler.handleEvent(evt); //compiler error

完成此运行时事件"dispatch"的最佳方法是什么?

最佳答案

你是对的,重载方法无法解决这个问题(因为要调用的方法是在编译时确定的)。

我建议您需要重构它,要么向将处理程序作为参数的 event 添加一个方法(类似于 public void act(EventHandler handler) ),或者重写您的处理程序,使其不需要强烈了解事件的类型。如果 Event 是一个合理的接口(interface)/父类(super class),它将公开足够的功能本身,以便 EventHandler 不需要需要了解特定类型。

如果您真的需要的话,当然可以随时进行强制转换,但一般来说,您应该遵循 Demeter 定律,并且仅通过 Event 接口(interface)与事件对象交互。

关于java - 如何将类的子类型的实例传递给相应的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159918/

相关文章:

c++ - 对虚重载函数感到困惑

c++ - 为什么要从 C++ 中删除 overload 关键字?

c++ - 使用默认值参数丢弃函数指针上的参数是否有效?

java - 在域对象生成器中进行 Spring 验证是个好主意吗?

java - 使用 SDL 将现有的 Lunar Lander 程序从 C 转换到 Android 手机

java - 如何从 solr 获取分片中的结果并将其存储在 hashmap 数组中

c++ - 从左值构造函数调用右值构造函数

c++ - 重载函数而不重写它们的整个定义

java - Wicket 面板析构函数 (Java)

java - 在 Java IDE 中停用 MEvent.CASE