java 實現回調代碼實例
JAVA實現回調
熟悉MS-Windows和X Windows事件驅動設計模式的開發(fā)人員,通常是把一個方法的指針傳遞給事件源,當某一事件發(fā)生時來調用這個方法(也稱為“回調”)。Java的面向對象的模型目前不支持方法指針,似乎不能使用這種方便的機制。
Java支持interface,通過interface可以實現相同的回調。其訣竅就在于定義一個簡單的interface,申明一個被希望回調的方法。
例如,假定當某一事件發(fā)生時會得到通知,我們可以定義一個interface:
public interface InterestingEvent { // 這只是一個普通的方法,可以接收參數、也可以返回值 public void interestingEvent(); }
這樣我們就有了任何一個實現了這個接口類對象的手柄grip。
當一事件發(fā)生時,需要通知實現InterestingEvent 接口的對象,并調用interestingEvent() 方法。
class EventNotifier { private InterestingEvent ie; private boolean somethingHappened; public EventNotifier(InterestingEvent event) { ie = event; somethingHappened = false; } public void doWork() {
if (somethingHappened) {
// 事件發(fā)生時,通過調用接口的這個方法來通知
ie.interestingEvent();
}
}
}
在這個例子中,用somethingHappened 來標志事件是否發(fā)生。
希望接收事件通知的類必須要實現InterestingEvent 接口,而且要把自己的引用傳遞給事件的通知者。
public class CallMe implements InterestingEvent { private EventNotifier en; public CallMe() { // 新建一個事件通知者對象,并把自己傳遞給它 en = new EventNotifier(this); } // 實現事件發(fā)生時,實際處理事件的方法 public void interestingEvent() { // 這個事件發(fā)生了,進行處理 } }
以上是通過一個非常簡單的例子來說明Java中的回調的實現。
當然,也可以在事件管理或事件通知者類中,通過注冊的方式來注冊多個對此事件感興趣的對象。
1. 定義一個接口InterestingEvent ,回調方法nterestingEvent(String event) 簡單接收一個String 參數。
interface InterestingEvent { public void interestingEvent(String event); }
2. 實現InterestingEvent接口,事件處理類
class CallMe implements InterestingEvent { private String name; public CallMe(String name){ this.name = name; } public void interestingEvent(String event) { System.out.println(name + ":[" +event + "] happened"); } }
3. 事件管理者,或事件通知者
class EventNotifier { private List<CallMe> callMes = new ArrayList<CallMe>(); public void regist(CallMe callMe){ callMes.add(callMe); } public void doWork(){ for(CallMe callMe: callMes) { callMe.interestingEvent("sample event"); } } }
4. 測試
public class CallMeTest { public static void main(String[] args) { EventNotifier ren = new EventNotifier(); CallMe a = new CallMe("CallMe A"); CallMe b = new CallMe("CallMe B"); // regiest ren.regist(a); ren.regist(b); // test ren.doWork(); } }
以上就是對Java回調機制的介紹,有需要的同學可以參考下。
相關文章
springboot如何使用@ConfigurationProperties封裝配置文件
springboot如何使用@ConfigurationProperties封裝配置文件的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08springboot vue組件開發(fā)實現接口斷言功能
這篇文章主要為大家介紹了springboot+vue組件開發(fā)實現接口斷言功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05Spring?Boot整合持久層之JdbcTemplate多數據源
持久層是JavaEE中訪問數據庫的核心操作,SpringBoot中對常見的持久層框架都提供了自動化配置,例如JdbcTemplate、JPA 等,MyBatis 的自動化配置則是MyBatis官方提供的。接下來分別向讀者介紹Spring Boot整合這持久層技術中的整合JdbcTemplate2022-08-08