mardi 4 juillet 2017

Generic Static Class as Service Locator

I am applying the Service Locator pattern as described in Game Programming Patterns, and am wondering about a possible generic implementation. The following code does work, but I am confused about using a class that is both generic and static.

The idea of the following C# code is to provide a "global" service to other parts of the application, exposing only an interface rather than the full implementation. Each service registered using this method will only have one instance in the application, but I want to be able to easily swap in/out different implementations of the provided interfaces.

My question is: when I use the following class to provide different services throughout my application, how does C# know that I am referring to different services of different types? Intuitively, I would almost think that the static variable, _service, would be overridden with each new service.

public static class ServiceLocator<T>
{
    static T _service;

    public static T GetService()
    {
        return _service;
    }

    public static void Provide(T service)
    {
        _service = service;
    }
}

Here's some usage:

// 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();

Aucun commentaire:

Enregistrer un commentaire