個人理解:回呼函數就是將一部分實現拋給客戶
package com.cy.test;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class WorkImpl { public void work(CallBack callBack) { System.out.println("work start..."); List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); callBack.execute(list); System.out.println(Arrays.toString(list.toArray())); } public static void main(String[] args) { WorkImpl work = new WorkImpl(); work.work(new CallBack() { public void execute(List<String> list) { list.add("haha"); } }); }}interface CallBack { void execute(List<String> list);}
下面來個例子:
package com.cy.test;import java.io.*;/** * 檔案上傳時回呼函數的例子 */public class UploadService { public void upload(UploadCallback callback) throws Exception { File f = new File("tmp-test.txt"); FileOutputStream out = new FileOutputStream(f); callback.send(out); } public static void main(String[] args) throws Exception { UploadService uploadService = new UploadService(); InputStream in = null; // 通過回調介面可以使實現更靈活 // 1 提供的參考實現1 uploadService.upload(new UploadStream(in)); // 2 提供的參數實現2 uploadService.upload(new UploadLocalFile("file")); // 3 ... // 4 使用時自己實現 uploadService.upload(new UploadCallback() { public void send(OutputStream out) throws IOException { // ... } }); }}/** * 回調介面 */interface UploadCallback { void send(OutputStream out) throws IOException;}/** * 通過IO流方式實現的回調 */class UploadStream implements UploadCallback { InputStream in; public UploadStream(InputStream in) { this.in = in; } public void send(OutputStream out) throws IOException { int readBytes; byte[] buff = new byte[256 * 1024]; try { while ((readBytes=in.read(buff)) >= 0) { if (readBytes == 0) { continue; } out.write(buff, 0, readBytes); } } finally { in.close(); } }}/** * 通過本地檔案實現的回調 */class UploadLocalFile implements UploadCallback { private String local_filename; public UploadLocalFile(String szLocalFilename) { this.local_filename = szLocalFilename; } public void send(OutputStream out) throws IOException { FileInputStream fis; int readBytes; byte[] buff = new byte[256 * 1024]; fis = new FileInputStream(this.local_filename); try { while ((readBytes = fis.read(buff)) >= 0) { if (readBytes == 0) { continue; } out.write(buff, 0, readBytes); } } finally { fis.close(); } }}