java中回调的实现

发布日期  发布: 2009-1-23 | 发布人  发布者: 游子 | 来源  来源: 江西广告网


//定义一个接口 interface Incrementable...{ void increment(); } //一个简单的接口实现类 class Callee1 implements Incrementable...{ private int i = 0; public void increment()...{ i ; System.out.println (i); } } class MyIncrement...{ void increment()...{ System.out.println ("other operator"); } static void f(MyIncrement mi) ...{ mi.increment(); } } //Callee2 想改变 MyIncrement中 increment()方法的行为。 // 主要是因为Callee2有一个完全不同的incr ()方法 // 要解决的问题是在调用increment 方法的时候 改而调用 incr方法 //父类有一个increment 不能因为字类的用途而覆盖这个方法 //所以字类重新写了一个 incr 方法。 class Callee2 extends MyIncrement...{ private int i = 0; //一个用来替代incrment方法的行为的方法。 private void incr()...{ i ; System.out.println (i); } //内部类实现Incrementable接口 private class Closure implements Incrementable ...{ public void increment()...{ incr(); } } //获得一个回调的引用 Incrementable getCallBackReference()...{ return new Closure(); } } class Caller...{ private Incrementable callbackReferences; //它只需要一个接口。 Caller (Incrementable chb)...{ callbackReferences = chb; } void go()...{ callbackReferences.increment(); } } class Callbacks...{ public static void main(String[] args)...{ Callee1 c1 = new Callee1(); Callee2 c2 = new Callee2(); MyIncrement.f(c2); Caller caller1 = new Caller(c1); //客户端完全不知道 caller2 中的incrment方法的实现。 //事实上Callee2完全改变了incrment方法的行为(调用了另一个方法) Caller caller2 = new Caller(c2.getCallBackReference()); caller1.go(); caller1.go(); caller2.go(); caller2.go(); } } //回调的价值在于它的灵活性--在运行时决定调用哪个方法。
本站文章部分内容来自互联网,供读者交流和学习,如有涉及作者版权问题请及时与我们联系,以便更正或删除。感谢所有提供信息的网站,并欢迎各类媒体与我们进行信息共享合作。
关闭本窗口 | 打印 | 收藏此页 |  推荐给好友 | 举报

版块排行

  • SEO搜索                                    5984
  • Web软件                                    3334
  • 交互设计                                    3279
  • 平面软件                                    2575
  • 设计欣赏                                    2501
  • 游戏世界                                    1244
  • 程序开发                                    830
  • 前沿视觉                                    560
  • 电脑网络                                    514
  • 摄影赏析                                    291