深入瞭解回呼函數Java

來源:互聯網
上載者:User

標籤:

        打回來。我第一次看到Java編程思想,後來Observer模式也適用於一個回呼函數的想法。但是,一直沒有重視,在處於劣勢的最終面試,越來越明白為什麼那麼多人說Java編程思想,這本書應該是一遍又一遍,。

        首先在網路上搜尋非常多文章介紹什麼是回呼函數。看的雲裡霧裡的。後來自己一步步分解最終理解了。記錄例如以下。

        從維基百科上面摘抄定義:(看完本篇文章再來理解這個定義)

        電腦程式設計中。回呼函數,或簡稱回調,是指通過

title=%E5%87%BD%E6%95%B0%E5%8F%82%E6%95%B0&action=edit&redlink=1">函數參數傳遞到其他代碼的。某一塊可運行代碼引用。這一設計同意了底層代碼調用在高層定義的子程式

        在Java裡面。我們使用介面來實現回調。

        這篇文章中的講解定義很好:http://blog.csdn.net/sweetwxh/article/details/2067139

        所謂的回調,就是程式猿A寫了一段程式(程式a),當中預留有回呼函數介面,並封裝好了該程式。

程式猿B要讓a調用自己的程式b中的一個方法。於是,他通過a中的介面回調自己b中的方法。

以下是範例。

      1.  首先定義一個類Caller,依照上面的定義就是程式猿A寫的程式a。這個類裡面儲存一個介面引用。

      

public class Caller {private MyCallInterface callInterface;public Caller() {}public void setCallFunc(MyCallInterface callInterface) {this.callInterface = callInterface;}public void call() {callInterface.printName();}}


       2.  當然須要介面的定義,為了方便程式猿B依據我的定義編敲代碼實現介面。

  

public interface MyCallInterface {public void  printName();}


      3.  第三是定義程式猿B寫的程式b

public class Client implements MyCallInterface {@Overridepublic void printName() {System.out.println("This is the client printName method");}}


       4.  測試例如以下

public class Test {public static void main(String[] args) {Caller caller = new Caller();caller.setCallFunc(new Client());caller.call();}}


      看到這裡應該明確什麼是回調了。有些文章介紹的非常好。可是剛開始沒看明確。是由於把第3步的類省略,直接寫成匿名類了。

        5.  在測試方法中直接使用匿名類。省去第3步。

public class Test {public static void main(String[] args) {Caller caller = new Caller();//caller.setCallFunc(new Client());caller.setCallFunc(new MyCallInterface() {public void printName() {System.out.println("This is the client printName method");}});caller.call();}}


      看完上面的文章後,。直接看下面的文章:http://kidult.iteye.com/blog/148982

      這些都是理解的回呼函數。

深入瞭解回呼函數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.