带字典的 JavaScript 策略模式

标签 javascript dictionary strategy-pattern

在 C# 中,我使用带有字典的策略模式,如下所示:

namespace NowListeningParserTool.Classes
{
using System.Collections.Generic;

public class WebsiteDictionary
{
    private readonly Dictionary<string, WebsiteParser> _website = new Dictionary<string, WebsiteParser>();

    public WebsiteDictionary()
    {
        _website.Add("YouTube", new YoutubeWebsiteParser());
        _website.Add("977 Music", new NineNineSevenMusicWebsiteParser());
        _website.Add("Grooveshark", new GroovesharkWebsiteParser());
        _website.Add("Sky.FM", new SkyfmWebsiteParser());
        _website.Add("iHeart", new IheartWebsiteParser());
        _website.Add("Live365", new LiveThreeSixFiveWebsiteParser());
        _website.Add("Pandora", new PandoraWebsiteParser());
        _website.Add("Spotify", new SpotifyWebsiteParser());
    }

    public string GetArtistAndTitle(string website, string browser, string stringToParse)
    {
        return _website[website].GetArtistAndTitle(browser, stringToParse, website);
    }

    public string GetWebsiteLogoUri(string website)
    {
        return _website[website].WebsiteLogoUri;
    }
}
}

WebsiteParser 是抽象类。

这在 JavaScript 中的语法是什么?例如,我在 JavaScript 中有多个 IF 语句:

function getWebsite() {
    if (document.URL.indexOf('grooveshark.com') >= 0) return getTrackGrooveshark();
    if (document.URL.indexOf('977music.com') >= 0) return getTrack977Music();
    if (document.URL.indexOf('sky.fm/play') >= 0) return getTrackSkyFm();
    if (document.URL.indexOf('iheart.com') >= 0) return getTrackIHeart();
    if (document.URL.indexOf('live365.com') >= 0) return getTrackLive365();
    if (document.URL.indexOf('youtube.com') >= 0) return getTrackYoutube();
    if (document.URL.indexOf('pandora.com') >= 0) return getTrackPandora();
    if (document.URL.indexOf('spotify.com') >= 0) return getTrackSpotify();
}

...我真的不喜欢,并且想使用与我在 C# 中相同的方法来消除这些丑陋的 IF。

干杯。

最佳答案

也许是这样的,但我没有足够的细节来知道这种方法是否适合你。但是,它展示了如何将对象用作键/值存储。

var fetchingStrategies = {
    'grooveshark.com': function () {
        return 'grooving!';
    },
    'youtube.com': function () {
        return 'youtubing!';
    }
};

//execute fetching strategy based on domain
fetchingStrategies['youtube.com']();

显然,您可以将硬编码的“youtube.com”字符串替换为一个变量,该变量将包含用于查找的正确域。

关于带字典的 JavaScript 策略模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18603181/

相关文章:

javascript - 不使用 JavaScript 下载文件

javascript - 从复杂数组中检索对象

字典 .title() 中的 Python 字典

c# - 一个简单的策略模式示例的问题

c# - 接口(interface)中具有不同参数的策略模式 (C#)

c++ - 正确使用 friend 来使用多种策略而不丢失状态?

JavaScript 对象 - 调用而不创建它(如 Math 对象)

javascript - 为什么即使页面经过审核,Lighthouse PWA 分数仍为空白

.net - 如何在 web.config 文件中存储字典对象?

swift - 如何在快速搜索字典时使用可选链接?