Enforce mapping of concrete classes of a common interface in a static map
Lets say I have an enum class - ConfigElement
which has some members like GENERAL_CONFIG("General Configuration")
, TRANSIT_TIMES("Transit times")
.
All of these config elements' individual classes, implement a common interface ConfigElementOP
, for example
开发者_StackOverflowpublic class TransitTimesOp implements ConfigElementsOp{
//implementation of interface methods
}
These individual classes define a certain behaviour which is particular to them.
Now, the controller of the application just gets the particular ConfigElement
, and then with the help of a factory, finds out the class which has the corresponding behaviour and uses it accordingly.
Currently, my factory is just a static map between the ConfigElement
and its behaviour class, like
public static Map<ConfigElement, ConfigElementsOp> ConfigElementBehaviourMap =
new HashMap<ConfigElement, ConfigElementsOp>();
ConfigElementBehaviourMap.put(ConfigElement.TRANSIT_TIMES, TransitTimesOp.class);
...
I have two concerns with this:
Is this the correct design for the factory? Seems messier to me, as addition of any new element and behaviour would require changes in multiple places and the miss to include it in this static map, would be silently ignored by the compiler.
Lets say we go with this design of the factory (static map), is there any way of enforcing that any new class defined for a config element, makes an entry into this map. And any such miss, would be a compile time error.
Usage can be described in the following way - Various controllers will require a different behavioural map of this enum. So, lets say - UI controller will have one map which states how to display a particular ConfigElement, Serializer will have another map at its disposal, which is a map between the ConfigElement and its particular serializer. Particular controllers when in work will get the corresponding behaviour for a ConfigElement from their map and use it.
Thanks in advance.
You can enhance the enums with a class parameter in addition to the existing string parameter, and retrieve the class directly from the enum. This is the way I would implement it.
First of all since the key is an enum you should probably use EnumMap
which is tailored for this case.
The static map will probably work at the cost of introducing a strong dependency between the class containing the map and the ConfigElementOp implementations.
What is the big picture, how are you going to use your Map
?
精彩评论