【问题标题】:Which design pattern to use to hit multiple rest api使用哪种设计模式来访问多个 rest api
【发布时间】:2017-10-21 21:12:54
【问题描述】:

我有一个问题需要帮助。

在我当前的应用程序中,我需要点击多个 rest api(来自 express)来获取数据并构建我的页面。 目前我正在使用 promise.all 从所有 api 端点获取数据。任何我可以放在上面的设计模式都可以帮助我解耦应用程序。

所以,我需要知道哪种设计模式最适合解决此类问题。

任何例子都会对我更有帮助。

提前致谢!

【问题讨论】:

  • 可能只需编写一点代码就可以解决所有问题设计模式
  • 是的,我也在问同样的问题,我应该使用哪种设计模式来解决这个问题。
  • Promise.all() 应该适用于多个 REST 调用。根本不清楚你要什么。关于代码的问题几乎总是应该显示您的代码,当您要求以比目前更好的方式做事时,这总是正确的。

标签: javascript express design-patterns


【解决方案1】:

我会建议你使用外观设计模式。 外观模式为用户提供了一个简单的界面,同时隐藏了它的底层复杂性。

Facade 模式非常适合将不同的 API 整合到一个单一的面向公众的接口中,该接口在后台与其他 API 连接。它在 JavaScript 中已经使用了很长时间了,你可能已经用过很多次了,甚至都不知道它。

下面是外观设计模式的基本示例:

'use strict';

var Mortgage = function(name) {
    this._name = name;
};

Mortgage.prototype = {
    apply: function(amount) {
        var result = 'Mortgage approved';
        if(!new Bank().verify(this._name, amount)) {
             result = 'Mortgage denied';
        } else if(!new Credit().verify(this._name, amount)) {
             result = 'Mortgage denied';
        } else if (!new Background().verify(this._name, amount)) {
            result = 'Mortgage denied';
        }
        return this._name + ' has been ' + result + ' for a ' + amount + ' mortgage';
    }
};

var Bank = function() {
    this.verify = function(name, amount) {
        // Implementation
        return true;
    };
};

var Credit = function() {
    this.verify = function(name, amount) {
        // Implementation
        return true;
    };
};

var Background = function() {
    this.verify = function(name, amount) {
        // Implementation
        return true;
    };
};

【讨论】:

    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多