java中闭包和回调
2013-11-03 16:11
375 查看
闭包是一个可调用的对象,他记录了一些信息,这些信息源自于创建他的作用域。所以可以看出内部类是面向对象的闭包,因为他不仅包含外围类的对象的信息,还有一个指向外围类的对象的引用。回调函数可以见博客:/article/1636617.html。好了下面我们可以看一下列子:
下面是具体的实现类:
package com.snail.innerclass.interf; /** * Created with IntelliJ IDEA. * User: mac * Date: 13-11-3 * Time: 下午3:11 * To change this template use File | Settings | File Templates. */ public interface Incrementable { void increment(); }
下面是具体的实现类:
package com.snail.innerclass.impl; import com.snail.innerclass.interf.Incrementable; /** * Created with IntelliJ IDEA. * User: mac * Date: 13-11-3 * Time: 下午3:12 * To change this template use File | Settings | File Templates. */ class Callee1 implements Incrementable{ private int i = 0; @Override public void increment() { i++; System.out.println("i = " + i); } } class MyIncrement { public void increment(){ System.out.println("other operation"); } static void f(MyIncrement increment){ increment.increment(); } } class Callee2 extends MyIncrement{ private int i =0; @Override public void increment() { super.increment(); i++; System.out.println("i = " + i); } private class Closure implements Incrementable{ @Override public void increment() { Callee2.this.increment(); } } Incrementable getCallbackReference(){ return new Closure(); } } class Caller{ private Incrementable callbackReference; Caller(Incrementable callbackReference) { this.callbackReference = callbackReference; } void go(){ callbackReference.increment(); } } public class Callbacks { public static void main(String[] args) { Callee1 callee1 = new Callee1(); Callee2 callee2 = new Callee2(); System.out.println("++++++++++++++++++++="); MyIncrement.f(callee2); Caller caller = new Caller(callee1); Caller caller1 = new Caller(callee2.getCallbackReference()); System.out.println("-------------------"); caller.go(); System.out.println("====================="); caller.go(); caller1.go(); caller1.go(); } }
相关文章推荐
- java变量
- Java设计模式—单态模式(Singleton)
- Ubuntu系统下运行Eclipse出现找不到jre的问题的解决方法
- eclipse wifi 连接手机
- Java基础知识整理(一)- Error和Exception
- 简易版基于Java的Servlet容器实现
- java poi 大批量数据处理,2007
- eclipse的debug
- Spring事务隔离级别和事务传播行为
- spring framework源码下载并导入eclipse
- failed to create the java virtual machine
- java,类方法访问小结
- 深入浅出Java多线程(2)-Swing中的EDT(事件分发线程) [转载]
- [安卓编译]JDK1.6 64位
- Spring AOP 实现和一些核心思想
- Java Classpath!
- java的外盒问题!
- hadoop学习笔记一之ubuntu下安装jdk
- Java Concurrent Lock锁
- java 上传文件(文本文件)