Reputation: 25755
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 ServerManager
s 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?
Upvotes: 3
Views: 1645
Reputation: 2635
What about defining an enum ServerIdentifier
for all possible Server-Types and in the interface:
ServerIdentifier getServerIdentifier();
Your map could then be a Map<ServerIdentifier, List<AbstractServer>>
and you would even be able to manage multiple instances of one Server-Type...
Advantage over using the Class-Object as a key would just be a more natural way of dealing with the server types, since you can use an enum and dont have to compare Class-Objects...
Upvotes: 0
Reputation: 500267
If you know there's ever going to be at most one instance per implementing class, then using the Class
object 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.
Upvotes: 3