如果您的速度具有整数增量,则在枚举对象中还有另一种具有预定义速度范围的解决方案。在双倍速度变化的情况下 11 到 10、61 到 60 并检查最小值作为排他值。
public enum SpeedMode {
LOW(0, 10), MEDIUM(11, 60), HIGH(61, 300);
private final int minSpeed;
private final int maxSpeed;
SpeedMode(int minSpeed, int maxSpeed) {
this.minSpeed = minSpeed;
this.maxSpeed = maxSpeed;
}
public int getMinSpeed() {
return this.minSpeed;
}
public int getMaxSpeed() {
return this.maxSpeed;
}
}
public class SpeedSelector {
private SpeedMode speedMode;
private boolean speedChanged;
public SpeedSelector() {
this.speedMode = SpeedMode.LOW;
this.speedChanged = true;
}
public void change(int speed) {
boolean validSpeed = false;
for (SpeedMode speedMode : SpeedMode.values()) {
if (speedMode.getMinSpeed() <= speed
&& speed <= speedMode.getMaxSpeed()) {
validSpeed = true;
if (this.speedMode != speedMode) {
speedChanged = true;
this.speedMode = speedMode;
break;
}
}
}
if (!validSpeed)
throw new IllegalArgumentException("Invalid speed range");
}
public SpeedMode getSpeedMode() {
return speedMode;
}
@Override
public String toString() {
if (speedChanged) {
speedChanged = false;
return "Speed changed to " + speedMode.name();
} else
return "";
}
}
public class TestClass {
public static void main(String[] args) {
SpeedSelector speedSelector = new SpeedSelector();
System.out.println(speedSelector);
speedSelector.change(23);
System.out.println(speedSelector);
speedSelector.change(25);
System.out.println(speedSelector);
speedSelector.change(100);
System.out.println(speedSelector);
speedSelector.change(150);
System.out.println(speedSelector);
speedSelector.change(10);
System.out.println(speedSelector);
}
}