1 回答
TA贡献1862条经验 获得超7个赞
基于您的原始概念...
const cities = {
NewYork: {
route1: 'U',
route2: 'C',
direction: (x, y)=>{
return {x:x+2, y:y*2};
},
},
LosAngeles: {
route1: 'U',
route2: 'C',
direction: (x, y)=>{
return {x:x+2, y:y*2};
},
},
};
enum如果您想要一组无法更改的预定义值,我会使用 POJO(普通的旧 Java 对象)或者可能使用 POJO 。
从一个Direction类开始,使这更简单......
public class Direction {
private int x;
private int y;
public Direction(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
并且可能是 enum
public enum City {
NEW_YORK("U", "C"),
LOS_ANGELES("U", "C");
private String route1;
private String route2;
private Cities(String route1, String route2) {
this.route1 = route1;
this.route2 = route2;
}
public Direction direction(int x, int y) {
return new Direction(x + 2, y * 2);
}
}
现在,如果您需要能够在运行时创建不同的城市,您可能会考虑更像......
public class City {
private String route1;
private String route2;
private City(String route1, String route2) {
this.route1 = route1;
this.route2 = route2;
}
public String getRoute1() {
return route1;
}
public String getRoute2() {
return route2;
}
public Direction direction(int x, int y) {
return new Direction(x + 2, y * 2);
}
}
请记住,您使用 OO 语言时,请利用可用的构造使您的生活更简单
添加回答
举报