【问题标题】:Java Inheritance DilemmaJava 继承困境
【发布时间】:2017-05-27 03:27:16
【问题描述】:

我目前正在开发一个基本上有两种变体的 Android SDK,基本变体(供第三方开发人员使用)和特权变体(供内部使用)。

特权 SDK 只是添加了第三方开发人员无法直接访问的附加功能。

我的想法是使用宏来选择性地删除功能,但 Java 不支持。

我的下一个想法是采用基本变体并在其中扩展类和接口以产生特权变体。

我当前的问题如下使用继承方法(这产生了一种代码味道,向我表明可能有更好的解决方案):

BaseAPI 的一个实例有一个BaseInterface 的实例,在它的某些方法中使用BaseDevice 作为参数。

特权 SDK 有一个 PrivilegedAPIPrivilegedInterfacePrivilegedDevice 的实例。

问题在于希望接口采用BaseDevicePrivilegedDevice 的任一实例。

我最喜欢这个 BaseInterface:

public interface BaseInterface {
    void deviceConnected(BaseDevice device);
}

还有这个 PrivilegedInterface:

public interface PrivilegedInterface extends BaseInterface {
    //overwrites deviceConnected in BaseInterface with PrivilegedDevice
    @Override
    void deviceConnected(PrivilegedDevice device);
}

但我不能在PrivilegedInterface 中用PrivilegedDevice 的不同参数覆盖deviceConnected

我的另一个想法是利用构建风格来隐藏功能,但这似乎也不适合。

有什么想法吗?

【问题讨论】:

    标签: java android inheritance


    【解决方案1】:

    在接口中创建一个额外的方法:(这是方法重载的概念)

    public interface BaseInterface {
        void deviceConnected(BaseDevice baseDevice);
        void deviceConnected(PrivilegedDevice privilegedDevice);
    

    }

    【讨论】:

    • PrivilegedDevice 不应该在 BaseInterface 中可用
    • 使特权设备(子)从基本设备(父)扩展。
    • 我已经这样做了,但是在回调方法中,设备被视为 BaseDevice,因此无法访问 PrivilegedDevice 中的方法
    【解决方案2】:

    我认为您需要抽象出设备类。

    public interface Device {
        void deviceConnected();
    }
    
    public class BaseDevice implements Device {
    
        BaseDevice() {
    
        }
    
        void deviceConnected() {
    
        }
    }
    
    public class PrivilegedDevice implements Device {
    
        PrivilegedDevice() {
    
        }
    
        void deviceConnected() {
    
        }
    }
    

    【讨论】:

    • 该接口用于回调,所以如果我理解你所说的正确,那么这不会解决问题
    【解决方案3】:

    这可能无法解决未来遇到相同问题的人的问题,但总体问题与我的类的层次结构和它们的一些内部结构有关。

    我实际上能够将一些东西移动到BaseAPI,摆脱在BaseDevice 中使用的类,并且基本上以更合乎逻辑的方式重组了东西。最终结果是更少的类和我的类的更合理的结构。

    代码异味是由于我的代码中有一些过于复杂的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      相关资源
      最近更新 更多