java 注册回调_java 实现回调代码实例
JAVA實(shí)現(xiàn)回調(diào)
熟悉MS-Windows和X Windows事件驅(qū)動(dòng)設(shè)計(jì)模式的開發(fā)人員,通常是把一個(gè)方法的指針傳遞給事件源,當(dāng)某一事件發(fā)生時(shí)來調(diào)用這個(gè)方法(也稱為“回調(diào)”)。Java的面向?qū)ο蟮哪P湍壳安恢С址椒ㄖ羔?#xff0c;似乎不能使用這種方便的機(jī)制。
Java支持interface,通過interface可以實(shí)現(xiàn)相同的回調(diào)。其訣竅就在于定義一個(gè)簡(jiǎn)單的interface,申明一個(gè)被希望回調(diào)的方法。
例如,假定當(dāng)某一事件發(fā)生時(shí)會(huì)得到通知,我們可以定義一個(gè)interface:
public interface InterestingEvent {
// 這只是一個(gè)普通的方法,可以接收參數(shù)、也可以返回值
public void interestingEvent();
}
這樣我們就有了任何一個(gè)實(shí)現(xiàn)了這個(gè)接口類對(duì)象的手柄grip。
當(dāng)一事件發(fā)生時(shí),需要通知實(shí)現(xiàn)InterestingEvent 接口的對(duì)象,并調(diào)用interestingEvent() 方法。
class EventNotifier {
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier(InterestingEvent event) {
ie = event;
somethingHappened = false;
}
public void doWork() {
if (somethingHappened) {
// 事件發(fā)生時(shí),通過調(diào)用接口的這個(gè)方法來通知
ie.interestingEvent();
}
}
}
在這個(gè)例子中,用somethingHappened 來標(biāo)志事件是否發(fā)生。
希望接收事件通知的類必須要實(shí)現(xiàn)InterestingEvent 接口,而且要把自己的引用傳遞給事件的通知者。
public class CallMe implements InterestingEvent {
private EventNotifier en;
public CallMe() {
// 新建一個(gè)事件通知者對(duì)象,并把自己傳遞給它
en = new EventNotifier(this);
}
// 實(shí)現(xiàn)事件發(fā)生時(shí),實(shí)際處理事件的方法
public void interestingEvent() {
// 這個(gè)事件發(fā)生了,進(jìn)行處理
}
}
以上是通過一個(gè)非常簡(jiǎn)單的例子來說明Java中的回調(diào)的實(shí)現(xiàn)。
當(dāng)然,也可以在事件管理或事件通知者類中,通過注冊(cè)的方式來注冊(cè)多個(gè)對(duì)此事件感興趣的對(duì)象。
1. 定義一個(gè)接口InterestingEvent ,回調(diào)方法nterestingEvent(String event) 簡(jiǎn)單接收一個(gè)String 參數(shù)。
interface InterestingEvent {
public void interestingEvent(String event);
}
2. 實(shí)現(xiàn)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 callMes = new ArrayList();
public void regist(CallMe callMe){
callMes.add(callMe);
}
public void doWork(){
for(CallMe callMe: callMes) {
callMe.interestingEvent("sample event");
}
}
}
4. 測(cè)試
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();
}
}
以上就是對(duì)Java回調(diào)機(jī)制的介紹,有需要的同學(xué)可以參考下。
總結(jié)
以上是生活随笔為你收集整理的java 注册回调_java 实现回调代码实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java对象生命周期_Java对象生命周
- 下一篇: java jfreechart下载_jf