事件:小菜中午打电话订外卖,然后继续干自己的工作。餐馆做好饭后打电话通知小菜收货。
首先定义送外卖业务协议:
public interface SendFood {
void sendFood(ReceiveFood receive,String foodName);
}
然后收外卖协议:
public interface ReceiveFood {
void receiveFood(Food food);
}
餐馆类:
public class Restaurant implements SendFood {
@Override
public void sendFood(ReceiveFood receive,String foodName) {
//告诉厨房做饭……
Food lunch=cook(foodName);
//将午餐送到你们约定的地点
receive.receiveFood(lunch);
}
private Food cook(String foodName){
//经过一段时间,一些美食已经错出来了
Food someFood=new Food(foodName);
return someFood;
}
}
小菜:
public class XiaoCai implements ReceiveFood {
private SendFood restaurant;
public XiaoCai(SendFood restaurant){
this.restaurant=restaurant;
}
public void orderFood(final String foodName){
new Runnable() {
@Override
public void run() {
restaurant.sendFood(XiaoCai.this,foodName);
}
}.run();
}
@Override
public void receiveFood(Food food) {
System.out.println("饭好了");
}
}
测试类:
public class Test {
public static void main(String[] args) {
SendFood sendFood = new Restaurant;
XiaoCai xc = new XiaoCai(sendFood);
xc.orderFood("炒饭");
}
}
意即类A的方法a调用了类B的方法b,而后b方法又调用了A中的方法a1。