I have a package-private interface called AbstractServer which offers three methods: start(), stop() and init().
For every new server, I implement the interface and override those methods. After that, I register this new server to my public ServerManager-class, which collects all servers in a HashMap and calls their exposed methods in a certain order.
So, starting all registered servers from somewhere else in the code simply looks like this:
ServerManager.INSTANCE.startServers();
The problem I’m currently facing is, that I want to be able to remove a Server from the ServerManagers map.
My idea was to introduce a public static final String IDENTIFIER-field to the interface and use it as the keys in the HashMap. This way, to remove a Server from the ServerManager, I would write:
ServerManager.INSTANCE.removeServer(HttpServer.IDENTIFIER);
The problem is, that I can’t have an “abstract” attribute in the interface and therefore can’t force the implementations to override it.
I can also not use a normal method (non-static) because the constructor of the Server-implementations will be package-private.
As an alternative, I thought about using the Class of the implementations as the keys in the HashMap so I can write something like this:
ServerManager.INSTANCE.removeServer(HttpServer.class);
Any thoughts on this?
If you know there’s ever going to be at most one instance per implementing class, then using the
Classobject as the key is a pretty natural solution.If you don’t, then clearly the IDs would have to be instance-specific and not class-specific.