前言
As we know JS支持"方法作為函數(shù)參數(shù)"专筷,所以回調(diào)方法很容易實(shí)現(xiàn),可是java并不支持跟磨。但在java式android編程中我們可以看到很多異步的回調(diào)翁狐。那么android是如何實(shí)現(xiàn)的呢瓣戚?在此我們并不討論類似RXJs、RXJava的新技術(shù)楞泼,只是用純?cè)膉ava思想實(shí)現(xiàn)回調(diào)
知識(shí)點(diǎn)
接口领追、多態(tài)、異步唬血、多線程望蜡、內(nèi)部類
正文
直接上代碼
package com.util.Super;
public class CallBackFnc {
/**
* 定義內(nèi)部接口用于回調(diào)
* @author wz
*
*/
interface Listener {
void OnListen();//無參回調(diào)
void OnListen(String s);//帶參回調(diào)
}
class A implements Listener {
static final String METHOD_ONE="方式一";
static final String METHOD_TWO="方式二";
static final String METHOD_THREE="方式三";
String type="默認(rèn)方式";
public A(String type) {
this.type=type;
}
/**
* 問問題
*/
public void Question() {
System.out.println("[A]:向B問問題");
//方式一
new Thread(new Runnable() {
public void run() {
System.out.println(METHOD_ONE);
//System.out.println("");
B b = new B();
b.answer(METHOD_ONE,5000,new Listener() {// 匿名內(nèi)部類 android很多基于此
public void OnListen(String s) {
System.out.println("[A]:"+METHOD_ONE+"獲取了答案:"+s);
System.out.println();
}
public void OnListen() {
}
});
}
}).start();
//方式二
new Thread(new Runnable() {
public void run() {
System.out.println(METHOD_TWO);
B b = new B();
b.answer(METHOD_TWO, 3000, new A(METHOD_TWO));
}
}).start();
//方式三
System.out.println(METHOD_THREE);
B b=new B();
b.answer(METHOD_THREE, 1000, this);
System.out.println("Question 執(zhí)行完畢");
}
@Override
public void OnListen(String s) {
System.out.println("[A]:"+this.type+"知道答案了: " + s);
System.out.println();
}
@Override
public void OnListen() {
}
}
class B {
/**
* 回答問題(耗時(shí)操作)
*/
public void answer(String name,int time,Listener listener) {
new Thread(new Runnable() {
public void run() {
try {
//Thread.sleep(time);
System.out.println("[B]:"+name+"向我問問題,B思考了"+time+"毫秒");
listener.OnListen(name+",我是B的子線程");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
//測(cè)試
public static void main(String[] args) {
CallBackFnc cbf = new CallBackFnc();
CallBackFnc.A a = cbf.new A("A from main");
a.Question();
System.out.println("main線程執(zhí)行完畢");
}
}
看一眼結(jié)果
測(cè)試結(jié)果
總結(jié)
多思考,多問問題拷恨,多動(dòng)手