java 闭包 回调_分析Java中的闭包与回调方法

闭包是一个可调用的对象,它记录了一些信息,这些信息来自于创建他的作用域,用过这个定义 可以看出内部类是面向对象的闭包 因为他不仅包含外围类对象的信息 还自动拥有一个指向此外围类对象的引用 在此作用域内 内部类有权操作所有的成员 包括private成员;

Java代码

interfaceIncrementable

{

voidincrement();

}

classCallee1implementsIncrementable

{

privateinti=0;

publicvoidincrement()

{

i++;

System.out.println(i);

}

}

classMyIncrement

{

voidincrement()

{

System.out.println("other increment");

}

staticvoidf(MyIncrement mi)

{

mi.increment();

}

}

classCallee2extendsMyIncrement

{

privateinti=0;

privatevoidincr()

{

i++;

System.out.println(i);

}

privateclassClosureimplementsIncrementable//内部类

{

publicvoidincrement()

{

incr();

}

}

Incrementable getCallbackReference()

{

returnnewClosure();//新建内部类

}

}

classCaller

{

privateIncrementable callbackRefference;

Caller(Incrementable cbh)

{

callbackRefference = cbh;

}

voidgo()

{

callbackRefference.increment();//调用increment()方法

}

}

publicclassCallbacks

{

publicstaticvoidmain(String [] args)

{

Callee1 c1=newCallee1();

Callee2 c2=newCallee2();

MyIncrement.f(c2);

Caller caller1 =newCaller(c1);

Caller caller2=newCaller(c2.getCallbackReference());//将内部类中的Closure赋给Caller

caller1.go();

caller1.go();

caller2.go();

caller2.go();

}

}

输出:

other increment

1

2

1

2

Callee2 继承字MyIncrement 后者已经有一个不同的increment()方法并且与Incrementable接口期望的increment()方法完全不相关 所以如果Callee2继承了MyIncrement 就不能为了Incrementable的用途而覆盖increment()方法 于是这能使用内部类独立的实现Incrementable

内部类Closure实现了Incrementable 一提供一个放回Caller2的钩子 而且是一个安全的钩子 无论谁获得此Incrementbale的引用 都只能调用increment() 除此之外没有其他功能。

希望通过本文的介绍,能给你带来帮助。

【编辑推荐】

【责任编辑:QiHappy TEL:(010)68476606】

点赞 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值