如何避免在此事件处理程序中重复代码?
How do I avoid repetitive code in this event handler?
我有一个 class 商店。
有多家商店,最终有数百家。
我有多个按钮使用一个事件处理程序,因为它们都做同样的事情,但数量不同,具体取决于商店。
我让事件处理程序检测哪个按钮触发了事件。
变量store
然后根据按下的按钮存储存储对象
但是检测按下哪个按钮的代码似乎非常重复。
以前差很多,我缩短了很多:
@FXML
private void handleButtonAction(ActionEvent event) {
Object source = event.getSource();
if (source.equals(store01Button)){
store = store01;
}else if (source.equals(store02Button)){
store = store02;
}else if (source.equals(store03Button)){
store = store03;
}else if (source.equals(store04Button)){
store = store04;
}else if (source.equals(store05Button)){
store = store05;
}else if (source.equals(store05Button)){
store = store05;
}
当我有数百家商店时,我正在寻找如何解决这个问题的答案。
一个简单的 "opinion":使用 Map<SomeButtonType, StoreType>
,其中 SomeButtonType 是源的类型,StoreType 是任何类型的商店,这会将您的总机处理程序减少到一到两行:
private void handleButtonAction(ActionEvent event) {
Object source = event.getSource();
store = myMap.get(source);
}
当然,您需要在创建按钮时填充地图,但这应该很容易。
创建按钮时使用 setUserData
保存对商店的引用。在事件处理程序中,使用 getUserData
获取它。每个 java fx 组件都维护一个属性映射。
我有一个 class 商店。
有多家商店,最终有数百家。
我有多个按钮使用一个事件处理程序,因为它们都做同样的事情,但数量不同,具体取决于商店。
我让事件处理程序检测哪个按钮触发了事件。
变量store
然后根据按下的按钮存储存储对象
但是检测按下哪个按钮的代码似乎非常重复。
以前差很多,我缩短了很多:
@FXML
private void handleButtonAction(ActionEvent event) {
Object source = event.getSource();
if (source.equals(store01Button)){
store = store01;
}else if (source.equals(store02Button)){
store = store02;
}else if (source.equals(store03Button)){
store = store03;
}else if (source.equals(store04Button)){
store = store04;
}else if (source.equals(store05Button)){
store = store05;
}else if (source.equals(store05Button)){
store = store05;
}
当我有数百家商店时,我正在寻找如何解决这个问题的答案。
一个简单的 "opinion":使用 Map<SomeButtonType, StoreType>
,其中 SomeButtonType 是源的类型,StoreType 是任何类型的商店,这会将您的总机处理程序减少到一到两行:
private void handleButtonAction(ActionEvent event) {
Object source = event.getSource();
store = myMap.get(source);
}
当然,您需要在创建按钮时填充地图,但这应该很容易。
创建按钮时使用 setUserData
保存对商店的引用。在事件处理程序中,使用 getUserData
获取它。每个 java fx 组件都维护一个属性映射。