首页 > 编程知识 正文

java回调地狱,java回调方法怎么显示

时间:2023-05-05 15:36:00 阅读:186429 作者:2270

在上一个故事中,我了解了如何解决java回调地狱问题,但在上一个故事中,我使用了Java abstract类的方式。 考虑到Java8的新功能lambda的可读性,今天我改写了使用lambda的方案。 大致的方式不变。 调用方法更改如下。

newpromise () _this,n )- {

system.out.println (hello 1n : ) n;

_this.resovle(1;

}.then((_this,n )-)。

system.out.println (hello 2n : ) n;

_this.resovle(2;

}.then((_this,n )-)。

system.out.println (hello 3n : ) n;

_this.resovle(3;

}.then((_this,n )-)。

system.out.println (hello 4n : ) n;

_this.resovle(4;

()、end );

当前方法使用构造函数,并向类Promise声明了一个lambda对象。 此方法的格式确实比前一个方法简单,但需要为前一个方法引入两个文件。

首先,需要引入CallBack.java的接口来接收lamdba对象。

包准备;

@ functional界面

公共接口调用{

voidrun(promise_this,int n;

() ) ) ) )。

然后,将Promise.java更改为以下文件:

包准备;

公共类属性{

private promise last promise=空;

privatepromisebeforepromise=null;

私有回调CB=null;

公共属性(

() ) ) ) )。

公共属性(callback CB ) {

this.cb=cb;

() ) ) ) )。

公共语音结束

反馈属性!=null ) {

beforePromise.end (;

} else { //找到第一个Promise对象并执行它

CB.run(this,0 );

() ) ) ) )。

() ) ) ) )。

publicpromisethen(callbackCB ) {

if(CB==null ) {

end (;

返回空值;

() ) ) ) )。

promiselastpromise=new promise (CB;

this.lastPromise=lastPromise; //为当前Promise对象指定下一个Promise对象引用

lastPromise.beforePromise=this; //分配以下Promise对象,然后引用上一个对象

返回最后属性;

() ) ) ) )。

publicvoidresovle(intn )//此处的n由参数用户传递给下一个run,可以根据需求类型进行更改

最后属性==null (if ) {

返回;

() ) ) ) )。

beforePromise=null; //清空上一个Promise的指针,以便gc更容易回收

lastpromise.CB.run(lastpromise,n ); //执行以下promise run方法

() ) ) ) )。

() ) ) ) )。

修正后的Promise仍然通过new的新Promise来实现,本来的执行效果如下

g :gradletestjava-jardistgradletest.jar

职业棒球联赛

hello1 n:0

hello2 n:1

hello3 n:2

hello4 n:3

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。