您好,欢迎访问沃航(武汉)科技有限公司官方网站
解决java回调地狱的方法二
2019-06-28 01:36:33

上一讲,我们了解了如何解决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


联系我们
地址:
武汉市洪山区蓝晶国际7栋903
QQ:
932773931
电话:
027-59761089-806
手机:
13397158231
邮箱:
jevian_ma@worldflying.cn
×
物联网组态平台
试用账号:123456
试用密码:123456
如需测试更多功能或者有疑问可发送邮件至:jevian_ma@worldflying.cn
×
积木编程平台
试用方式:试用手机号码注册即可使用
如需测试更多功能或者有疑问可发送邮件至:jevian_ma@worldflying.cn