在 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/