您的位置:首页 > 其它

设计模式之回调模式

2016-08-11 14:11 239 查看
public class Demo {
public static void main(String [] args){
Server s=new Server();
Client c=new Client();
c.haveLaunch(s);
}
}

interface Money{
public int getMoney();
}
class Server {
public void cookTomotoWithEgg(Money money){
if(money.getMoney()>8)
System.out.println("做西红柿炒蛋");
else
System.out.println("不做西红柿炒蛋");
}
}
class Client {
public void haveLaunch(Server server){
server.cookTomotoWithEgg(new Money() {
@Override
public int getMoney() {
// TODO Auto-generated method stub
System.out.println("付款7元");
return 7;
}
});
server.cookTomotoWithEgg(new Money() {

@Override
public int getMoney() {
// TODO Auto-generated method stub
System.out.println("付款11元");
return 11;
}
});
}
}


Client类的方法调用Server类的方法,而Server类的方法调用接口Money的方法,Money接口的方法在Client类的方法中匿名实现.这就造成Clent执行Server中的代码,Server执行Client中的代码,看起来像他们互相调用一样,因此叫回调模式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: