一些建议:
1. 由于x,y的组合,有五种状态;您可以使用枚举类型来定义这些状态;
2. 如果您想在代码中减少if...else语句,请参考状态机设计模式;但我认为,在您的情况下,状态非常简单,不需要使其过于复杂。
public class Status {
public enum Direction {
SOUTH_WEST((x, y) -> y > 0 && x < 0, "Travelling South-West")
, SOUTH_EAST((x, y) -> y >0 && x > 0, "Travelling South-East")
, NORTH_EAST((x, y) -> x > 0 && y < 0, "Travelling North-East")
, NORTH_WEST((x,y) -> x < 0 && y < 0, "Travelling North-West"), CENTER((x,y) -> x == 0 && y == 0, "");
BiPredicate<Integer, Integer> bp;
String desc;
public BiPredicate<Integer, Integer> getBp() {
return bp;
}
public void setBp(BiPredicate<Integer, Integer> bp) {
this.bp = bp;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private Direction(BiPredicate<Integer, Integer> bp, String desc) {
this.bp = bp;
this.desc = desc;
}
public static Direction getDirection(int x, int y) {
for (Direction direction : Direction.values()) {
if(direction.getBp().test(x, y)) {
return direction;
}
}
return null;
}
}
public static void main(String[] args) {
Direction d = Direction.getDirection(3, 4);
System.out.println(d.getDesc());
}
}
North/South
部分和East/West
部分分配给两个字符串,然后打印一个包含这两个字符串的消息。 - khelwood