java地狱_解决java回调地狱的方法

上一讲,我们了解了如何解决java的回调地狱的问题,但是上一讲我们使用的是java的abstract类的方式。考虑到Java8新特性lambda的可读性,今天我改写一个使用lambda的方案,大体方式不变,调用方法改为如下:

new Promise((_this, n) -> {

System.out.println("hello1 n:" + n);

_this.resovle(1);

}).then((_this, n) -> {

System.out.println("hello2 n:" + n);

_this.resovle(2);

}).then((_this, n) -> {

System.out.println("hello3 n:" + n);

_this.resovle(3);

}).then((_this, n) -> {

System.out.println("hello4 n:" + n);

_this.resovle(4);

}).end();

可以看到,现在的方法使用的是构造函数,声明一个lambda对象给类Promise,本方法的写法确实比之前的方法简洁,但是相对之前的方法,却需要引入两个文件。

首先需要引入一个CallBack.java的接口用于接收lamdba对象。

package REDIS;

@FunctionalInterface

public interface CallBack {

void run(Promise _this, int n);

}

然后修改Promise.java为如下文件:

package REDIS;

public class Promise {

private Promise lastPromise = null;

private Promise beforePromise = null;

private CallBack cb = null;

public Promise () {

}

public Promise (CallBack cb) {

this.cb = cb;

}

public void end () {

if (beforePromise != null) {

beforePromise.end();

} else { // 寻找第一个Promise对象,然后执行它

cb.run(this, 0);

}

}

public Promise then (CallBack cb) {

if (cb == null) {

end ();

return null;

}

Promise lastPromise = new Promise(cb);

this.lastPromise = lastPromise; // 赋值当前的Promise对象下一个Promise对象引用

lastPromise.beforePromise = this; // 赋值下一个Promise对象,它的上一个对象引用

return lastPromise;

}

public void resovle (int n) { // 这里的n是一个参数用户传递给下一个run,根据需求类型可以更改

if (lastPromise == null) {

return;

}

beforePromise = null; // 将上一个Promise的指针置空,方便gc回收

lastPromise.cb.run(lastPromise, n); // 执行下一个Promise的run方法

}

}

可以看到,经过修改的Promise依旧是通过new一个新的Promise来实现的,本来嘛的执行效果如下:

G:\gradletest>java -jar dist\\gradletest.jar

Hello world

hello1 n:0

hello2 n:1

hello3 n:2

hello4 n:3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值