0

As per the title, which is the best and most efficient way to implement event handling?

  1. creating the listener object as an inner class
  2. by using the this keyword
  3. using an anonymous class for the event listener
2
  • If the listener is short, you can create an anonymous inner class by using a lambda. If the listener is longer or more complicated, create a separate class implementing ActionListener. Apr 18, 2022 at 16:55
  • Even better, implement Action.
    – Kayaman
    Apr 18, 2022 at 17:01

1 Answer 1

0

You can use Observer pattern. For example:

    public class Observer {
        private String state;

        public void update(String state) {
            this.setState(state);
        }
    }

    public class Observed {
        private String state;
        private List<Observer> observers = new ArrayList<>();

        public void addObserver(Observer observer) {
            this.observers.add(observer);
        }

        public void removeObserver(Observer observer) {
            this.observers.remove(observer);
        }

        public void setState(String state) {
            this.state = state;
            for (Observer observer : this.observers) {
                observer.update(this.state);
            }
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.