初识-----------事件,实现与原理
,字⾯上的理解就是监听观察某个事件(程序)的发⽣情况,当被监听的使劲按真的发⽣了的时候,事件发⽣者(事件源)就会给注册该事件的监听者()发送消息,告诉监听者某些消息,同时监听者页获得⼀份事件对象,根据这个对象可以获得相关属性和执⾏相关操纵。
模型涉及有三个对象
1. 事件:⽤户对组件的⼀个操作,或者说程序执⾏某个⽅法,称之为⼀个事件,如机器⼈程序执⾏⼯作。
2. 事件源:发⽣事件的组件就是事件源,也就是被监听对象,如机器⼈可以⼯作,跳舞
3. 事件的处理器:监听并负责处理事件⽅法,如监听机器⼈的⼯作情况,机器⼈⼯作前后做出的反应
执⾏顺序如下:
1. 将事件源注册到
2. 组件接受外部作⽤,也就是事件触发
3. 产⽣⼀个事件对象,并将事件对象传递给,由监听处理器进⾏处理。
母亲节快乐的英语4. 执⾏相关的代码来处理该事件。
模式:事件源注册之后,当事件源触发事件,就可以回调使劲按对象的⽅法;更形象的说,监听模式是基于:注册-回调事件/消息通知处理模式,就是被监控者将消息通知给所有监控者。
1. 注册:事件源。setListener
2. 回调:事件源实现onListener.
下⾯是⼀个模仿的demo,需求:事件机器⼈⼯作和跳舞在机器⼈⼯作和跳舞之前添加相关的提⽰
package com.botListener;
2
3 /**
4 * 事件源:机器⼈
5 */
军运会时间6 public class Robot {
7
8 private RobotListener listener;
无领导小组面试9
10 /**
11 * 注册机器⼈
12 * @param listener
13 */
14 public void registerListener(RobotListener listener){
15 this.listener = listener;
16 }
17
18 /**
19 * ⼯作
20 */
21 public void working(){
22 if(listener!=null){
23 Even even = new Even(this);
24 this.listener.working(even);
25 }
26 System.out.println("机器⼈开始⼯作......");
27 }
28
29 /**
30 * 跳舞
31 */
32 public void dancing(){
33 if(listener!=null){
34 Even even = new Even(this);
35 this.listener.dancing(even);
36 }
37 System.out.println("机器⼈开始跳舞......");
38 }
网上转账要手续费吗39
40
41 }
创建Event对象
package com.botListener;
2
3 /**
4 * 事件对象
5 */
6 public class Even {
7
8 private Robot robot;
9
10 public Even(){
11 super();
12 }
13 public Even(Robot robot){
14 super();
15 bot = robot;
16 }
17
18
19 public Robot getRobot() {
20 return robot;
21 }
22
23 public void setRobot(Robot robot) {
24 bot = robot;
25 }
26 }
创建接⼝RobotListener
package com.botListener;
2
3 /**
4 * 事件
5 */
6 public interface RobotListener {
7
8 public void working(Even even);
9 public void dancing(Even even);
10 }
实现事件MyRobotllistener
package com.botListener;
2
3 public class MyRobotListener implements RobotListener{
4 @Override
5 public void working(Even even) {
6 Robot robot = Robot();
7 System.out.println("机器⼈⼯作提⽰:请看管好的你机器⼈,防⽌它偷懒!");
8 }
9
10 @Override
11 public void dancing(Even even) {今年冬奥会金牌榜
战狮
12 Robot robot = Robot();
13 System.out.println("机器⼈跳舞提⽰:机器⼈跳舞动作优美,请不要⾛神哦!");
14 }
15 }
package com.botListener;
2
3 public class TestListener {
4
5 public static void main(String[] args) {
6 Robot robot = new Robot();
7 isterListener(new MyRobotListener());
8 robot.working();
9 robot.dancing();
10 }
11 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论