我在这个 Node.js 代码示例中使用了什么模式

What pattern am I using in this example of Node.js code?

本文关键字:模式 什么 Node 代码 js      更新时间:2023-09-26
'use strict';
var type = {};
type.image = require('./search.image.js');
type.video = require('./search.video.js');
type.social = require('./search.social.js')
function search (query, formatter, type) {
    var objectToUse = type['type'];
    objectToUse.setFormatter = formatter;
    objectToUse.setQuery = query;
    objectToUse.exec(function(response) {
        return response;
    });
}

我正在尝试为不同类型的媒体动态调用自制搜索引擎。它需要不同的解析器,并以通用格式返回数据。我很好奇我正在使用什么类型的模式。如果每个搜索引擎都使用通用代码,我将使用mixin。但是,我很好奇唤起每个模式的最佳模式是什么?而且,这最像哪种模式?

这似乎是策略模式。来自维基百科:

在计算机编程中,策略模式(也称为 策略模式(是一种软件设计模式,可实现 要在运行时选择的算法行为。

策略模式 定义一系列算法,封装每个算法,并使 该系列中的算法可互换。战略让 算法因使用它的客户端而异。[1] 战略是 有影响力的书籍《设计模式》中包含的模式之一 由Gamma等人推广了使用模式的概念 描述软件设计。

https://en.wikipedia.org/wiki/Strategy_pattern

我从这段代码中了解到,@James Gaunt 对策略的看法似乎是正确的。这可能是实现它的更好方法,您不需要不需要的代码:

'use strict';
function search (query, formatter, type) {
    var objectToUse = require('./search.' + type + '.js');
    objectToUse.setFormatter = formatter;
    objectToUse.setQuery = query;
   objectToUse.exec(function(response) {
        return response;
    });
}