调用API的SDK相关知识:实现回调函数.
熟悉MS-Windows和X Windows事件驅動設計模式的開發人員,通常是把一個方法的指針傳遞給事件源,當某一事件發生時來調用這個方法(也稱為“回調”)。Java的面向對象的模型目前不支持方法指針,似乎不能使用這種方便的機制。
Java支持interface,通過interface可以實現相同的回調。其訣竅就在于定義一個簡單的interface,申明一個被希望回調的方法。
例如,假定當某一事件發生時會得到通知,我們可以定義一個interface:
public interface InterestingEvent {
??? // 這只是一個普通的方法,可以接收參數、也可以返回值
??? public void interestingEvent();
}
這樣我們就有了任何一個實現了這個接口類對象的手柄grip。
當一事件發生時,需要通知實現InterestingEvent?接口的對象,并調用interestingEvent()?方法。
class EventNotifier {
??? private InterestingEvent ie;
??? private boolean somethingHappened;
??? public EventNotifier(InterestingEvent event) {
??? ??? ie = event;
??? ??? somethingHappened = false;
??? }
??? public void doWork() {
??? ??? if (somethingHappened) {
??? ??? ??? // 事件發生時,通過調用接口的這個方法來通知
??? ??? ??? ie.interestingEvent();
??? ??? }??? ????
??? }
}
在這個例子中,用somethingHappened?來標志事件是否發生。
希望接收事件通知的類必須要實現InterestingEvent?接口,而且要把自己的引用傳遞給事件的通知者。
public class CallMe implements InterestingEvent {
??? private EventNotifier en;
??? public CallMe() {
??? ??? // 新建一個事件通知者對象,并把自己傳遞給它
??? ??? en = new EventNotifier(this);
??? }
??? // 實現事件發生時,實際處理事件的方法
??? public void interestingEvent() {
??? ??? // 這個事件發生了,進行處理
??? }
}
以上是通過一個非常簡單的例子來說明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();??? ????
??? }
}
總結
以上是生活随笔為你收集整理的调用API的SDK相关知识:实现回调函数.的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: boost在DevC++中的安装过程
- 下一篇: 回调设计模式