Class A实现接口CallBack callback——背景1
class A中包含一个class B的引用b ——背景2
class B有一个参数为callback的方法f(CallBack callback) ——背景3
1. 异步的回调机制
public interface CallBack {
public abstract void solve(String result);
}
public class Wang implements CallBack {
private Li li;
public Wang(Li li) {
this.li = li;
}
public void askQuestion(final String question) {
System.out.println("ask question : ");
new Thread(new Runnable() {
@Override
public void run() {
li.executeMessage(Wang.this, question);
}
}).start();
play();
}
public void play() {
System.out.println("i am out to do something.");
}
@Override
public void solve(String result) {
System.out.println("The answer is " + result);
}
}
public class Li {
public void executeMessage(CallBack callBack, String question) {
System.out.println("the question is :" + question);
for (int i=0; i<10000; i++) {
}
String result = "the answer is 2";
callBack.solve(result);
}
}
public class TestLi {
public static void main(String[] args) {
Li li = new Li();
Wang wang = new Wang(li);
wang.askQuestion("1+1 = ? ");
}
}
interface CallBack{ //相当于接口InA
public void doCRUD();
}
public class A implements CallBack{//【背景1】
private B b;//【背景2】
public void doCRUD(){
System.out.println("执行add操作...");
}
public void add(){
b.execute(new A());//【you call me】
}
}
public class B{
public void execute(CallBack action){ //【背景3】
getConnection();
action.doCRUD(); //【i call you back】
releaseConnection();
}
public void getConnection(){
System.out.println("获得连接...");
}
public void releaseConnection(){
System.out.println("释放连接...");
}
}