您的位置:首页 > 编程语言 > Java开发

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();
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: