简体   繁体   中英

How do I avoid repetitive code in this event handler?

I have a class Store.

There are multiple stores, eventually hundreds.

I have multiple buttons using one event handler since they all do the same, but with different numbers depending on the store.

I have the event handler detect which button triggered the event.

The variable store then stores the store object depending on the button pressed

But the code to detect which button was pressed seems extremely repetitive.

It used to be a lot worse, I shortened it a lot:

@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;
    }

I am looking for an answer on how to fix this problem when I have hundreds of stores.

One simple "opinion": use a Map<SomeButtonType, StoreType> where SomeButtonType is the type of the source, and StoreType is whatever type store is which would reduce your switchboard handler to a one to two lines:

private void handleButtonAction(ActionEvent event) {
    Object source = event.getSource();
    store = myMap.get(source);
}

Of course you would need to fill the map on creation of your buttons, but that should be easy.

When creating the button use setUserData to save reference to the store. In the event handler, use getUserData to get it. Each of the java fx components maintain a map of properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM