c# - 按名称获取服务
问题描述
我有一个 .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 语句?也许使用依赖注入是可能的,但我不太清楚该怎么做。或者有某种设计模式可以做到这一点。
解决方案
你可以有一个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 原则中的要点。
我使用了 GameSericeBase 的函数,因为它与问题中的完全一样,该函数在每次调用中都会返回一个新实例。
推荐阅读
- ruby-on-rails - Youtube 嵌入 - Ruby on rails
- opencv3.0 - Flir Duo - 热图像到温度矩阵的转换
- sql - Oracle 日期操作
- python - 使用 Dask 处理大型压缩 csv 文件
- android - 使用 Bazel 和 j2objc 在 iOS 和 Android 之间共享代码
- swift - 如何在 Swift 中创建多个块实例?
- python - 仅为功能创建 django 应用程序
- java - Windows 10 任务栏位置
- node.js - Google/Firebase 云功能的速率限制?
- php - 刮掉破碎的图像并加入它们以制作用于电子书创作的完整图像