我有一个.Net Core游戏项目。在任何API中,我都希望通过为其指定游戏名称(或ID)来获得特定于游戏的服务。我目前有以下内容:
public GameServiceBase GetGameService(string gameName)
{
switch (gameName)
{
case GameNames.Keno:
return new KenoService();
case GameNames.BetOnPoker:
return new BetOnPokerService();
case GameNames.Minesweeper:
return new MinesweeperService();
default:
throw new Exception();
}
}
比方说,我们有更多的游戏服务,我只列出了一些,但您知道了。有没有比使用switch语句更好的获取服务的方法了?也许可以使用依赖注入,但是我不太清楚该怎么做。或者有某种设计模式可以做到这一点。
答案 0 :(得分:1)
您可以拥有Dictionary
中的GameNames, Func<GameServiceBase>
。
它将是这样的:
static Dictionary<GameNames,Func<GameServiceBase>> dict = new Dictionary<GameNames,Func<GameServiceBase>>();
// can be in object creation
dict.Add(GameNames.Keno, () => new KenoService());
.
.
public GameServiceBase GetGameService(string gameName)
{
// handle here case of wrong game name
...
return dict[gameName];
}
优点是,此解决方案是动态的,而不是像交换机一样静态的解决方案。 这正是Open Closed principle中的要点。
我使用了GameSericeBase函数,因为它与问题完全相同,该函数在每次调用时都会返回一个新实例。