Creating Custom Listeners In Java

前端 未结 2 1180
南笙
南笙 2020-12-30 05:18

I was wondering how it would be possible to create my own listener for something, and to be able to use it just like any other listener, ex.

public interface         


        
相关标签:
2条回答
  • 2020-12-30 05:56

    Here is a short example:

        private static class Position {
        }
    
        private static class Ball {
            private ArrayList<FootballObserver> observers = new ArrayList<FootballObserver>();
            private Position ballPosition = new Position();
    
            public void registerObserver(FootballObserver observer) {
                observers.add(observer);
            }
    
            public void notifyListeners() {
                for(FootballObserver observer : observers) {
                    observer.notify(ballPosition);
                }
            }
    
            public void doSomethingWithFootballPosition() {
                //bounce etc
                notifyListeners();
            }
        }
    
        private static interface FootballObserver {
            void notify(Position ball);
        }
    
        private static class Player implements FootballObserver {
            public void notify(Position ball) {
                System.out.println("received new ball position");
            }
        }
    
        public static void main(String... args) {
            FootballObserver player1 = new Player();
            Ball football = new Ball();
            football.registerObserver(player1);
            football.doSomethingWithFootballPosition();
        }
    
    0 讨论(0)
  • 2020-12-30 06:13

    There is no trouble creating the listeners that you need, but you only can apply it to classes that expect it (so you cannot do (new Object()).addMyListener)

    You will need to add to the classes where you want to use the listener an addMyListener(MyListener myListener) method. It just stores the listeners that you pass to it in a list for later user. It would be a good idea creating an interface with the addMyListener method (and a fireMyListeners()) method too.

    Of course, you must also provide the code to call the fireMyListeners() method, too. Then the fireMyListeners() will just loop through the listeners and call theirs notification method.

    0 讨论(0)
提交回复
热议问题