I have multiple classes in my current project like HTMLRequest
, SPDYRequest
, BHIVERequest
. I get data from a network stream and I want to find out, which of the classes can handle this data. For this I read the header of the Stream packet (All protocols are in the same form, so I can read until I get empty line (\r\n) ) and then pass this header to a static function in the request classes which returns a boolean which tells whether it is a header for this kind of request or not. Now I want to be able to load specific Protocols at runtime (from plug-ins). What is the best way to be able to check whether I have a Protocol for a header or not.
My thoughts were:
An extra class Protocol
as a singleton, which then is registered in a RequestFactory
, that then has to find out which Protocol can create a request for this kind of header and calls Protocol.assemble()
A static List of Class<? extends Request>
so I can call the static methods through reflection or by Class.newInstance()
I don't like both that ideas, so what is the right way to dynamically do this stuff in Java?
If it were me, I'd do something similar, but not identical, to option 1:
HashMap
in a RequestFactory
or similarly named utility. You'd also store references to the built-in system protocols in this map.RequestFactory.getProtocol(String header)
to grab a reference to the protocol that should be used.Note that if you go this route, you don't need a method in each protocol class that lets you query whether a header is appropriate for it; the factory handles that for you.
Edit
...I just noticed the "at runtime" part of your question, which makes the "at startup" part of my solution a little out of place. New plugins could still be registered into the factory's internal map as they're recognized/loaded; that shouldn't affect the usefulness of this design as a whole.