Skip to main content

Generic Service Locator in Java for Game Development

ServiceLocator is a very useful decoupling pattern to avoid too many Singletons. It's structure is always the same, so I thought it should be possible to create a generic one, to decrease code duplication. Well, here is what I've come up with,  guess someone with more knowledge about generics could create something better, but it is better than nothing.

PS: I thought it must be possible to have a static method generating NulServices / Stub Services in the Classes implementing IService, but I couldn't find out how to demand a static method createNullService in an interface. Tell me if you have an idea.

Here ist the abstract ServiceLocator


import java.util.HashMap;
import java.util.Map;

/**
 * IServiceLocator
 *
 * @author Georg Eckert 2017
 */

public abstract class ServiceLocator
{
    private final Map<Class<? extends IService>, IService> services, nullServices;


    public ServiceLocator()
    {
        services = new HashMap<>();
        nullServices = new HashMap<>();
        provideNullServices();
    }

    public abstract void provideNullServices();

    public <T extends IService> T get(Class<T> serviceInterface)
    {
        if(!services.containsKey(serviceInterface) && !nullServices.containsKey(serviceInterface))
        {
            throw new IllegalArgumentException("No such Service in this Module.");
        }

        if(services.containsKey(serviceInterface))
            return (T) services.get(serviceInterface);
        else {
            System.err.println("SERVICES: No " + serviceInterface.getSimpleName() + " service injected, returning NullService.");
            return (T) nullServices.get(serviceInterface);
        }
    }

    public <T extends IService> void provide(T service , Class<? extends IService> serviceInterface)
    {
        services.put(serviceInterface, service);
    }

    public <T extends IService> void provideNull(T service , Class<? extends IService> serviceInterface)
    {
        nullServices.put(serviceInterface, service);
    }
}

and a concrete one, overriding the abstract provideNullServices method


import de.limbusdev.utils.ServiceLocator;

/**
 * GuardiansServiceLocator
 *
 * @author Georg Eckert 2017
 */

public class ConcreteServiceLocator extends ServiceLocator
{
    private ServiceLocator instance;

    public ServiceLocator getInstance()
    {
        if(instance == null) instance = new ConcreteServiceLocator();
        return instance;
    }

    @Override
    public void provideNullServices()
    {
        provideNull(new AbstractFactory()
            {
                @Override
                public AbstractProduct createProduct(int ID)
                {
                    return null;
                }
            },
            AbstractFactory.class
        );
    }
}

all real services must be provided somewhere in your initialization code

// Providing a concrete Service
ConcreteServiceLocator.provide(new ConcreteFactory());

// Retrieving the concrete service without knowing its exact implementation
AbstractFactory factory = ConcreteServiceLocator.getService(AbstractFactory.class);

Comments

Popular posts from this blog

Newer Super Mario Bros. Wii unter Linux mit Patchimage

Super Mario Bros. ist ein Klassiker. Dazu muss sicher nicht viel gesagt werden. Doch auch die neuesten Ableger der Serie wie New Super Mario Bros. Wii erfreuen sich großer Beliebtheit. Eine Weile lang machte ein Spiel namens Newer Super Mario Bros. Wii großes Aufsehen. Die Forsetzung zum Original von Nintendo wurde inoffiziell vom Newer-Team in 3-jähriger Entwicklerarbeit erstellt, hat 128 neue Level und überzeugt durch die außerordentliche Qualität des Hacks. An dieser Stelle sei gesagt, dass ihr das Spiel nur legal spielen könnt, wenn ihr New Super Mario Bros. Wii selbst besitzt. Falls dies nicht der Fall ist, kauft es bitte zuerst. Illegal heruntergeladene Spiele werden nicht unterstützt und von mir ausdrücklich nicht befürwortet . (Eine Windows-Anleitung findet ihr hier: WiiDatabase .de) Also, los gehts: Dumpt euer originales New Super Mario Bros. Wii z.B. mit USB Loader GX (auf + klicken) kopiert den Ordner New Super Mario Bros. Wii [SMNP01] auf euren PC Nun ...

Ubuntu 16.04 USB-Stick - "Das Ziel ist schreibgeschützt" lösen

Es gibt Dinge, die dürfen in einem nutzerfreundlichen Betriebssystem einfach nicht passieren. Vor allem dürfen Sie aber nicht monatelang bestehen bleiben. Mit Ubuntu 16.04 kann ich Freunden und Bekannten Ubuntu einfach nicht mehr empfehlen, wenn selbst ich an einfachsten Aufgaben scheitere. Gemeint ist hier das Kopieren von Dateien auf USB-Sticks. Trotz jahrelanger Ubuntu/Linux-Erfahrung gelang es mir erst nach gründlicher Recherche das Problem zu beheben. Ein Laie hat hier keine Chance. Damit ihr nicht lange suchen müsst, hier das Problem samt Lösung: Problem Datei oder Ordner auf Fat32-USB-Stick kopieren oder anlegen schlägt fehl mit der Meldung "Das Ziel ist schreibgeschützt". Lösung das Paket fuse-posixovl installieren und Ubuntu neu starten sudo apt-get install fuse-posixovl Viel Erfolg

[Unreal Engine][C++] How to create a simple trigger actor

[Unreal Engine][C++] How to create a simple trigger actor A Simple Trigger Volume in C++ Used Unreal Engine Version: 4.22 This is the first post of a small series of Unreal Engine C++ Tutorials. Keep in mind, that Unreal’s API changes rapidly and often. I still hope, this may be of some use to others. Coming from Unity, programming in C++ for Unreal is rather painful. I hope to give you some assistance and make life a little bit easier. Whay, would you say, should we make our own trigger actor? There is ATriggerVolume , right? Yes, there is, but inheriting from it is difficult and rather undocumented. I tried and failed. Yes, we have to give up some of ATriggerVolume 's functionality, but we learn a lot and at least we know exactly what it’s doing. First, we’ll create a new C++ class, inheriting from Actor , called SimpleTriggerVolume . Let’s add a protected property to hold a reference to our trigger component: /** Shape of the trigger volume componen...