• 手写一个监听器


    1.事件对象

    public class Even {
    
        private Robot robot;
    
        public Even() {
            super();
        }
    
        public Even(Robot robot) {
            super();
            this.robot = robot;
        }
    
    
        public Robot getRobot() {
            return robot;
        }
    
        public void setRobot(Robot robot) {
            this.robot = robot;
        }
    }

    2.事件源:机器人 

    public class Robot {
    
        private RobotListener listener;
    
        /**
         * 注册机器人监听器
         *
         * @param listener
         */
        public void registerListener(RobotListener listener) {
            this.listener = listener;
        }
    
        /**
         * 工作
         */
        public void working() {
            if (listener != null) {
                Even even = new Even(this);
                this.listener.working(even);
            }
            System.out.println("机器人开始工作......");
        }
    
        /**
         * 跳舞
         */
        public void dancing() {
            if (listener != null) {
                Even even = new Even(this);
                this.listener.dancing(even);
            }
            System.out.println("机器人开始跳舞......");
        }
    }

    3.事件监听器

    public interface RobotListener {
    
        void working(Even even);
    
        void dancing(Even even);
    }

    4.自定义监听器

    public class MyRobotListener implements RobotListener {
    
        @Override
        public void working(Even even) {
            Robot robot = even.getRobot();
            System.out.println("机器人工作提示:请看管好的你机器人,防止它偷懒!");
        }
    
        @Override
        public void dancing(Even even) {
            Robot robot = even.getRobot();
            System.out.println("机器人跳舞提示:机器人跳舞动作优美,请不要走神哦!");
        }
    }

    5.测试类

    public class TestListener {
    
        public static void main(String[] args) {
            Robot robot = new Robot();
            robot.registerListener(new MyRobotListener());
            robot.working();
            robot.dancing();
        }
    }
  • 相关阅读:
    如何判断两个数组是否相等?
    正则表达式
    开发板 Linux驱动视频 驱动是什么
    关于模型的评估
    Python画图参数设置
    Python图片的横坐标汉字
    矩阵的点成和叉乘
    svd 奇异值分解
    Python的主成分分析PCA算法
    论文参考文献格式
  • 原文地址:https://www.cnblogs.com/ason-wxs/p/13386775.html
Copyright © 2020-2023  润新知