Thinking in java-30 Closure and Callback闭包和回调

1. What is callback and closure is?

Thinking in java 中的内部类章节中有关于‘闭包和回调’的内容,简单做一下整理。这里有关此问题的详细stackoverflow上Q&A, 及在thinking in java上的笔记内容。
闭包:闭包是一种从它被创建的作用范围内保留信息的可以调用的对象。从该定义可以看出,内部类是一种面向对象的闭包,因为它不仅包含外部类对象的所有信息(这就是所谓的它被创建出来的范围),而且它还保存整个外部类对象的引用,它有权限操作所有的成员(包括private 成员)。
回调:java中关于引入指针机制所引发的最大争议就是允许了所谓的–’callback’回调机制。 在回调过程中,一些信息传递给其他的对象,并允许其在将来的某个时刻回调原本的对象。

2. A java demo adapted from ‘thinking in java’

这个例子挺长,为何选这个例子作为callback的demo呢?
首先,Caller提供的函数是以Increment接口为参数类型的,而Callee2并没有显式implement Increment接口,所以这里通过了内部类的方式实现了这个机制。

package com.fqy.blog;

/*
 * A simple interface with a method increment().
 */
interface Incrementable {
    void increment();
}

/*
 * A simple class that implements interface Incrementable.
 */
class Callee1 implements Incrementable {
    private int i = 0;

    @Override
    public void increment() {
        i++;
        System.out.println("In Callee1: " + i);
    }
}

/*
 * A new class with a method increment() and a static method f() which takes a
 * MyIncrement object as its parameter.
 * 
 */
class MyIncrement {
    void increment() {
        System.out.println("In MyIncrement: Other operation!");
    }

    static void f(MyIncrement mi) {
        mi.increment();
    }
}

/*
 * Another class that extends class MyIncrement, contains a method increment()
 * 
 */
class Callee2 extends MyIncrement {
    private int i = 0;

    private void incr() {
        i++;
        System.out.println("In Callee2: " + i);
    }

    private class Closure implements Incrementable {
        @Override
        public void increment() {
            incr();
        }
    }

    Incrementable getCallbackReference() {
        return new Closure();
    }
}

class Caller {
    private Incrementable callbackReference;

    Caller(Incrementable cbh) {
        callbackReference = cbh;
    }

    void go() {
        callbackReference.increment();
    }
}

public class Callbacks {
    public static void main(String[] args) {
        Callee1 c1 = new Callee1();
        Callee2 c2 = new Callee2();
        MyIncrement.f(c2);
        Caller caller1 = new Caller(c1);
        Caller caller2 = new Caller(c2.getCallbackReference());

        caller1.go();
        caller1.go();
        caller2.go();
        caller2.go();
    }
}

//Running result:
In MyIncrement: Other operation!
In Callee1: 1
In Callee1: 2
In Callee2: 1
In Callee2: 2

3. 个人理解

  • closure闭包是我们如何build的方式,而callback是我们如何使用的方式。Closure is how you build it, callback is how you use it.
  • 回调callback可以通过闭包closure的方式实现,或者通过实现接口的方式。
  • 回调意味着,我们可以传递给一段代码给一个函数,这个函数可以在将来某个时候调用那一段代码。这是一种特殊的参数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值