感謝作者,本文轉載來自:https://www.cnblogs.com/againn/p/9512013.html
監聽器,字面上的理解就是監聽觀察某個事件(程序)的發生情況,當被監聽的使勁按真的發生了的時候,事件發生者(事件源)就會給注冊該事件的監聽者(監聽器)發送消息,告訴監聽者某些消息,同時監聽者頁獲得一份事件對象,根據這個對象可以獲得相關屬性和執行相關操縱。
監聽器模型涉及有三個對象
1. 事件:用戶對組件的一個操作,或者說程序執行某個方法,稱之為一個事件,如機器人程序執行工作。
2. 事件源:發生事件的組件就是事件源,也就是被監聽對象,如機器人可以工作,跳舞
3. 事件的監聽器處理器:監聽並負責處理事件方法,如監聽機器人的工作情況,機器人工作前后做出的反應
執行順序如下:
1. 將事件源注冊到監聽器
2. 組件接受外部作用,也就是事件觸發
3. 產生一個事件對象,並將事件對象傳遞給監聽器,由監聽處理器進行處理。
4. 監聽器執行相關的代碼來處理該事件。
監聽器模式:事件源注冊監聽器之后,當事件源觸發事件,監聽器就可以回調使勁按對象的方法;更形象的說,監聽模式是基於:注冊-回調事件/消息通知處理模式,就是被監控者將消息通知給所有監控者。
1. 注冊監聽器:事件源。setListener
2. 回調:事件源實現onListener.
下面是一個模仿監聽器的demo,需求:事件機器人工作和跳舞在機器人工作和跳舞之前添加相關的提示
package com.ssm.listener.robotListener; 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.ssm.listener.robotListener; 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 this.robot = robot; 16 } 17 18 19 public Robot getRobot() { 20 return robot; 21 } 22 23 public void setRobot(Robot robot) { 24 this.robot = robot; 25 } 26 }
創建監聽器接口RobotListener
package com.ssm.listener.robotListener; 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.ssm.listener.robotListener; 2 3 public class MyRobotListener implements RobotListener{ 4 @Override 5 public void working(Even even) { 6 Robot robot = even.getRobot(); 7 System.out.println("機器人工作提示:請看管好的你機器人,防止它偷懶!"); 8 } 9 10 @Override 11 public void dancing(Even even) { 12 Robot robot = even.getRobot(); 13 System.out.println("機器人跳舞提示:機器人跳舞動作優美,請不要走神哦!"); 14 } 15 } package com.ssm.listener.robotListener; 2 3 public class TestListener { 4 5 public static void main(String[] args) { 6 Robot robot = new Robot(); 7 robot.registerListener(new MyRobotListener()); 8 robot.working(); 9 robot.dancing(); 10 } 11 }