My Blog

手写一个监听器

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();
    }
}
posted @ 2020-05-28 20:10  王心森  阅读(180)  评论(0编辑  收藏  举报