classB{ /** * 计算结果 * @author xiaodu.email@gmail.com * @param a * @param question */ publicvoidanswer(final A a, final String question){ if (question.equals("What is the answer to life, the universe and everything?")) { a.processResult("42"); } } }
/** * 相互调用 * @author xiaodu.email@gmail.com * */ publicclassSyncObjectCallback{ publicstaticvoidmain(final String[] args){ B b = new B(); A a = new A();
a.ask(b, "What is the answer to life, the universe and everything?"); } }
classB{ publicvoidanswer(final A a, final String question){ if (question.equals("What is the answer to life, the universe and everything?")) { a.processResult("42"); } } }
/** * 面向对象的相互调用 * @author xiaodu.email@gmail.com * */ publicclassSyncOOCallback{ publicstaticvoidmain(final String[] args){ B b = new B(); A a = new A(b); a.ask("What is the answer to life, the universe and everything?"); } }
@Override publicvoidrecvAnswer(final String answer){ System.out.println(answer); } } /** * 面向接口的同步回调 * @author xiaodu.email@gmail.com * */ publicclassSyncInterfaceCallback{ /** * 使用内部类来实现的方式 * @author xiaodu.email@gmail.com */ privatestaticvoidinnerMain(){ Server server = new Server(); server.answer(new IClient() { @Override publicvoidrecvAnswer(final String answer){ System.out.println(answer); } }, "What is the answer to life, the universe and everything?"); }
publicstaticvoidmain(final String[] args){ Server server = new Server(); ClientSync client = new ClientSync(server); client.ask("What is the answer to life, the universe and everything?");
@Override publicvoidrecvAnswer(final String answer){ System.out.println(answer); } } /** * 基于接口的异步回调,每次建立新的线程 * @author xiaodu.email@gmail.com * */ publicclassAsyncInterfaceCallback{ /** * 使用内部类的实现方式,此处可见回调地狱 * @author xiaodu.email@gmail.com */ privatestaticvoidinnerMain(){ Server server = new Server();
new Thread(new Runnable() { @Override publicvoidrun(){ server.answer(new IClient() { @Override publicvoidrecvAnswer(final String answer){ System.out.println(answer); } }, "What is the answer to life, the universe and everything?"); } }).start(); System.out.println("asked ! waiting for the answer..."); }
publicstaticvoidmain(final String[] args){ Server server = new Server(); ClientAsync client = new ClientAsync(server); client.ask("What is the answer to life, the universe and everything?"); System.out.println("asked ! waiting for the answer...");
for (int i = 0; i < 100; i++) { ClientRunnable cr = new ClientRunnable(server, "What is the answer to life, the universe and everything?", i); es.execute(cr); System.out.println("client " + i + " asked !"); }