一個簡單的java回呼函數的實現

來源:互聯網
上載者:User

標籤:業務   call   技術分享   new t   target   static   cal   span   解釋   

回呼函數回呼函數涉及的3個函數登記回呼函數
回呼函數
響應回呼函數
簡單的解釋你到一個商店買東西,剛好你要的東西沒有貨,於是你在店員那裡留下了你的電話。過了幾天店裡有貨了,店員就打了你的電話,然後你接到電話後就到店裡去取了貨。在這個範例裡,你的電話號碼就叫回呼函數。你把電話留給店員就叫登記回呼函數,店裡後來有貨了叫做觸發了回調關聯的事件。店員給你打電話叫做調用回呼函數,你到店裡去取貨叫做響應回調事件。回答完成。來自知乎點擊開啟連結

代碼的實現首先有一個介面 interface CallBack,當然沒有也是能夠的,主要是用來預定義商務邏輯
public interface CallBack {/* * 響應回呼函數 */public void slove();}

然後是上面介面的實現,登記回調和響應回調的實作類別
public class A implements CallBack {B b = new B();@Override/* * (non-Javadoc) * @see CallBack#slove() * 響應回呼函數 */public void slove() {System.out.println("the problem is solve!");}/* * 登記回呼函數 */public void askQuestion(){System.out.println("ask b solve the problem!");/* * 自己去做其它事 */new Thread(new Runnable() {@Overridepublic void run() {System.out.println("A want to do another thing!");}}).start();/* * ask b to solve this problem */this.b.call(this);}/* * test */ public static void main(String[] args)  {A a = new A();a.askQuestion();}}

然後就是實現回呼函數的類
public class B {/* * 回呼函數 */public void call(CallBack a){/* * b help a solve the priblem */System.out.println("b help a solve the problem!");/* * call back */a.slove();}}

測試結果


一個簡單的java回呼函數的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.