【发布时间】:2017-12-08 06:22:24
【问题描述】:
我将服务定位器模式应用为described in Game Programming 模式,并且想知道可能的通用实现。以下代码确实有效,但我对使用通用和静态的类感到困惑。
以下 C# 代码的想法是为应用程序的其他部分提供“全局”服务,只公开一个接口而不是完整的实现。使用此方法注册的每个服务在应用程序中只有一个实例,但我希望能够轻松地换入/换出所提供接口的不同实现。
我的问题是:当我使用以下类在整个应用程序中提供不同的服务时,C# 怎么知道我指的是不同类型的不同服务?直觉上,我几乎认为静态变量 _service 会被每个新服务覆盖。
public static class ServiceLocator<T>
{
static T _service;
public static T GetService()
{
return _service;
}
public static void Provide(T service)
{
_service = service;
}
}
这里有一些用法:
// Elsewhere, providing:
_camera = new Camera(GraphicsDevice.Viewport);
ServiceLocator<ICamera>.Provide(_camera);
// Elsewhere, usage:
ICamera camera = ServiceLocator<ICamera>.GetService();
// Elsewhere, providing a different service:
CurrentMap = Map.Create(strategy);
ServiceLocator<IMap>.Provide(CurrentMap);
// Elsewhere, using this different service:
IMap map = ServiceLocator<IMap>.GetService();
【问题讨论】:
-
public static class ServiceLocator<T>这意味着你有很多封闭类型的ServiceLocator'1。因此,如果您使用ServiceLocator<ICamera>和ServiceLocator<IMap>,您将拥有两个static T _service;对象。你是对的,当你使用ServiceLocator<T>.Provide时,它会重写`_service;` 的值,但它只会重写封闭类型ServiceLocator'1的值。这意味着ServiceLocator<IMap>.Provide(CurrentMap)将重写static IMap _service;,但在上述情况下不会重写static ICamera _service; -
我有一个通用服务定位器,用于依赖注入不可用的情况。明天我有工作电脑后会发布。
-
@ScottHannen 谢谢,那太好了!
标签: c# oop design-patterns static monogame