我有一个类,它有几个代表不同类型设备名称的枚举。
public class DeviceNames {
public enum Microsoft {
DeviceName1, DeviceName2, DeviceName3
}
public enum Apple {
DeviceName1, DeviceName2, DeviceName3
}
}
我有不同具体设备将实现的接口(接口指定它可以通信的方式)
public interface IPDevice{
//factory method
Device createNewIPDevice(DeviceNames.Enum<E> deviceName);
}
public interface USBDevice{
//factory method
Device createNewUSBDevice(DeviceNames.Enum<E> deviceName);
}
我有一个抽象类
public abstract class Device {
String deviceName;
protected Device(String deviceName) {
this.deviceName = deviceName;
}
}
实现一个或多个接口的抽象类的具体实现
public class MicrosoftDevice implements IPDevice{
@Override
public Device createNewIPDevice(DeviceNames.Microsoft deviceName) {
return super(deviceName.toString());
}
}
public class AppleDevice implements IPDevice, USBDevice {
@Override
public Device createNewIPDevice(DeviceNames.Apple deviceName) {
return super(deviceName.toString());
}
@Override
public Device createNewUSBDevice(DeviceNames.Apple deviceName) {
return super(deviceName.toString();
}
}
我想使用枚举来确保它们只提供有效的设备名称(而不是传递给字符串)
如何让接口方法采用一个可以采用通用枚举类型但只包含DeviceNames类中的枚举的参数?
答案 0 :(得分:0)
我问了一个跟进问题here。接受的答案解决了这个问题。
引用@Andreas(回答另一个问题的人)
您使接口本身实际上采用通用参数
工作代码如下所示(此处未包含的代码保持不变):
public interface IPDevice<DeviceName extends Enum> {
//factory method
Device createNewIPDevice(DeviceName deviceName);
}
public interface USBDevice<DeviceName extends Enum> {
//factory method
Device createNewUSBDevice(DeviceName deviceName);
}
public class MicrosoftDevice implements IPDevice<DeviceNames.Microsoft> {
@Override
public Device createNewIPDevice(DeviceNames.Microsoft deviceName) {
return super(deviceName.toString());
}
}
public class AppleDevice implements IPDevice<DeviceNames.Apple>, USBDevice<DeviceNames.Apple> {
@Override
public Device createNewIPDevice(DeviceNames.Apple deviceName) {
return super(deviceName.toString());
}
@Override
public Device createNewUSBDevice(DeviceNames.Apple deviceName) {
return super(deviceName.toString();
}
}