【发布时间】:2021-08-14 03:43:43
【问题描述】:
我正在尝试找到一种方法来减少长度并简化以下重复方法:
boolean circleFlag, squareFlag, diamondFlag;
public void shapeButtonPressed(String shapeType) {
if (shapeType.equals("Circle")) {
circlePressed();
} else if (shapeType.equals("Square")) {
squarePressed();
} else if (shapeType.equals("Diamond")) {
diamondPressed();
}
}
public void circlePressed() {
if(!circleFlag){
//set only circleFlag true and the rest false.
circleFlag = true;
squareFlag = false;
diamondFlag = false;
//(... some code)
} else {
//set all flags false.
circleFlag = false;
diamondFlag = false
squareFlag = false;
//(... some different code)
}
}
public void squarePressed() {
if(!squareFlag){
//set only squareFlag true and the rest false.
squareFlag = true;
circleFlag = false;
diamondFlag = false;
//(... some code)
} else {
//set all flags false.
circleFlag = false;
diamondFlag = false
squareFlag = false;
//(... some different code)
}
}
public void diamondPressed() {
if(!diamondFlag){
//set only diamondFlag true and the rest false.
diamondFlag = true;
squareFlag = false;
circleFlag = false;
//(... some code)
} else {
//set all flags false.
circleFlag = false;
diamondFlag = false
squareFlag = false;
//(... some different code)
}
}
我尝试过的事情
我尝试将我的所有值设置为Boolean 类型,将它们设置为ArrayList<Boolean> 并将shapePressed(String shapeType) 方法更改为
public void shapePressed(String shapeType) {
Boolean currFlag = false;
if (shapeType.equals("Circle")) {
currFlag = circleFlag;
} else if (shapeType.equals("Square")) {
currFlag = squareFlag;
} else if (shapeType.equals("Diamond")) {
currFlag = diamondFlag;
}
if (!currFlag){
for (Boolean flag : shapeFlag) flag = ( flag == currFlag ) ? true : false;
//(...)
} else {
for (Boolean flag : shapeFlag) flag = false;
//(...)
}
}
但( flag == currFlag ) 行将布尔值作为值而不是单个对象进行比较。所以我的currFlag在上面这个方法中是没有意义的。
然后我虽然使用HashMap<String ,Boolean>,但是每当我比较给定键的值(来自方法参数的字符串 shapeType)时,我都会遇到与上述相同的问题。
有什么方法可以简化这段代码?
【问题讨论】:
-
您可以直接使用
circleFlag = !circleFlag;而不是if (circleFlag) { ...},然后将其他标志设置为false。 -
可能有很多方法可以实现这一点,但我可能会建议使用 Enum 来表示您的不同形状并存储代表当前形状的 Enum 类型的
currFlag。跨度>